For example i have a file:
$ cat file
i am the first example.
i am the second line.
i do a question about a file.
and i need:
example, line, file
i intent with "awk" but the problem is that the words are in different space
For example i have a file:
$ cat file
i am the first example.
i am the second line.
i do a question about a file.
and i need:
example, line, file
i intent with "awk" but the problem is that the words are in different space
tldr;
For a file like this
the given command will print
How it works:
awk '{print $NF}'
: prints the last field of every linepaste -sd,
: readsstdin
serially (-s
, one file at a time) and writes fields comma-delimited (-d,
)sed 's/,/, /g'
:s
ubstitutes","
with", "
g
lobally (for all instances)References:
Try
To get the result in one line as in your example, try:
output:
Pure bash:
Another way of doing this in plain bash is making use of the
rev
command like this:Basically, you reverse the lines of the file, then split them with
cut
using space as the delimiter, take the first field thatcut
produces and then you reverse the token again, usetr -d
to delete unwanted chars andtr
again to replace newline chars with,
Also, you can avoid the first cat by doing:
You can do it easily with grep:
(
-E
use extended regex;-o
output only the matched text instead of the full line)You can do something like this in awk:
Edit: To avoid empty line :
there are many ways. as
awk
solutions shows, it's the clean solutionsed solution is to delete anything till the last space. So if there is no space at the end, it should work
sed 's/.* //g' <file>
you can avoid
sed
also and go for awhile
loop.it reads a line, reveres it, cuts the first (i.e. last in the original) and restores back
the same can be done in a pure bash way
it is called parameter expansion