Remove all text before last space in text file from CLI
7,136
Solution 1
There's a lot of choice using the command line:
$ echo "2015-03-02 21:34:15 20480 dump-2015-03-02-21-34.tar" | cut -c32-
dump-2015-03-02-21-34.tar
$ echo "2015-03-02 21:34:15 20480 dump-2015-03-02-21-34.tar" | sed 's/.* //'
dump-2015-03-02-21-34.tar
$ echo "2015-03-02 21:34:15 20480 dump-2015-03-02-21-34.tar" | grep -oP "\S+$"
dump-2015-03-02-21-34.tar
$ echo "2015-03-02 21:34:15 20480 dump-2015-03-02-21-34.tar" | awk {'print $NF'}
dump-2015-03-02-21-34.tar
$ echo "2015-03-02 21:34:15 20480 dump-2015-03-02-21-34.tar" | perl -pe 's/.* //'
dump-2015-03-02-21-34.tar
$ echo "2015-03-02 21:34:15 20480 dump-2015-03-02-21-34.tar" | rev | cut -d ' ' -f 1 | rev
dump-2015-03-02-21-34.tar
Solution 2
sed
is by default greedy, so just remove everything until the last space:
sed 's/.* //'
or use this awk
idiom:
awk '$0=$NF'
Solution 3
Try grep
:
echo "2015-03-02 21:34:15 20480 dump-2015-03-02-21-34.tar" | grep -Eo "[^ ]+$"
You can also use tr
and cut
together:
echo "2015-03-02 21:34:15 20480 dump-2015-03-02-21-34.tar" | tr -s ' ' | cut -d' ' -f4
Why should python
be left behind:
python2 -c 'print "2015-03-02 21:34:15 20480 dump-2015-03-02-21-34.tar".split()[3]'
All of the above produce output: dump-2015-03-02-21-34.tar
Related videos on Youtube
Author by
Admin
Updated on September 18, 2022Comments
-
Admin almost 2 years
I want to remove everything before the last space in a text file from the CLI
Example text:
2015-03-02 21:34:15 20480 dump-2015-03-02-21-34.tar
The string that should remain is
dump-2015-03-02-21-34.tar