Reputation: 107
I have a script that has uses cut
to pick some information out of a search that contains absolute paths. It looks something like:
PLACE=$(grep foo flatfile.txt | cut -d '/' -f 1-6)
The output looks like this:
machine1:/path/to/where/foo/is
machine2:/another/path/to/find/foo
I need it to look like this:
machine1:/path/to/where/foo/is/
machine2:/another/path/to/find/foo/
This needs to be printed to the console at the end of the script with echo "$PLACE"
or something like that. The output will always be at least 2 lines, but usually more.
I tried about everything I can think of with echo, but it either shows no output at all or gives the output:
grep: '/' is a directory
I am running bash 3.00 on Solaris, if that helps any. I would really like to K.I.S.S. this by just having something tacked onto the end of the cut command, and not having to monkey with sed or awk. But, if that is the only way, so be it.
Upvotes: 5
Views: 5865
Reputation: 16016
You can use one sed
command, instead of multiple other commands:
$ PLACE=$(sed -n '/foo/s:\(\([^/]\+/\)\{6\}\)\(.*\)\+:\1:p' flatfile.txt)
$ echo "$PLACE"
machine1:/path/to/where/foo/is/
machine2:/another/path/to/find/foo/
$
... and then I'm reminded of why sed
sometimes makes me shudder :-/
Upvotes: 0
Reputation: 23374
Try the following. Note that $PLACE
is not quoted. This should allow word-splitting to happen and each word (which corresponds to one line of your output, assuming no embedded spaces) is then printed by printf
with a following /
and newline. Haven't been able to test this on Bash 3 on Solaris though
printf "%s/\n" $PLACE
Upvotes: 0
Reputation: 1482
try this :
PLACE=$(grep foo flatfile.txt | cut -d '/' -f 1-6 | xargs -I "%" echo %/)
Upvotes: 4