Reputation: 63
I want to remove the first two words that come up in my output string. this string is also within another string.
What I have:
for servers in `ls /data/field`
do
string=`cat /data/field/$servers/time`
This sends this text:
00:00 down server
I would like to remove "00:00 down" so that it only displays "server".
I have tried using cut -d ' ' -f2- $string
which ends up just removing directories that the command searches.
Any ideas?
Upvotes: 6
Views: 11702
Reputation: 1032
For the examples given, I prefer cut. But for the general problem expressed by the question, the answers above have minor short-comings. For instance, when you don't know how many spaces are between the words (cut), or whether they start with a space or not (cut,sed), or cannot be easily used in a pipeline (shell for-loop). Here's a perl example that is fast, efficient, and not too hard to remember:
| perl -pe 's/^\s*(\S+\s+){2}//'
Perl's -p
operates like sed's. That is, it gobbles input one line at a time, like -n
, and after dong work, prints the line again. The -e
starts the command-line-based script. The script is simply a one-line substitute s///
expression; substitute matching regular expressions on the left hand side with the string on the right-hand side. In this case, the right-hand side is empty, so we're just cutting out the expression found on the left-hand side.
The regular expression, particular to Perl (and all PLRE derivatives, like those in Python and Ruby and Javascript), uses \s
to match whitespace, and \S
to match non-whitespace. So the combination of \S+\s+
matches a word followed by its whitespace. We group that sub-expression together with (...)
and then tell sed to match exactly 2 of those in a row with the {m,n}
expression, where n is optional and m is 2. The leading \s*
means trim leading whitespace.
Upvotes: 0
Reputation: 185151
Please, do the things properly :
for servers in /data/field/*; do
string=$(cut -d" " -f3- /data/field/$servers/time)
echo "$string"
done
$( )
ls
output, use glob
instead like I do with data/field/*
Check http://mywiki.wooledge.org/BashFAQ for various subjects
Upvotes: 11
Reputation: 26667
Use -d
option to set the delimtier to space
$ echo 00:00 down server | cut -d" " -f3-
server
Note Use the field number 3
as the count starts from 1
and not 0
From man page
-d, --delimiter=DELIM
use DELIM instead of TAB for field delimiter
N- from N'th byte, character or field, to end of line
More Tests
$ echo 00:00 down server hello world| cut -d" " -f3-
server hello world
The for
loop is capable of iterating through the files using globbing. So I would write something like
for servers in /data/field*
do
string=`cut -d" " -f3- /data/field/$servers/time`
...
...
Upvotes: 6