Reputation: 1150
I have a file test.txt
like this (but containing many more lines)
/foo/bar/how hello
/foo/bar/are hello
/foo/bar/you hello
I want to get this output:
/foo/bar/how how
/foo/bar/are are
/foo/bar/you you
I have tried this:
while read line
do
bla=$(echo $line | cut -f4 -d"/" | cut -f1 -d" ")
sed -i "s/hello/$bla/"
done <test.txt
But the output is:
sed: no input files
sed: no input files
sed: no input files
When I provide the filename (while read line; do bla=$(echo $line | cut -f4 -d"/" | cut -f1 -d" "); sed -i "s/hello/$bla/" test.txt ; done <test.txt
), I get this:
/foo/bar/how how
/foo/bar/are how
/foo/bar/you how
I would like to replace on each line some constant pattern by a pattern appearing before on the same line and that changes from line to line. Any idea on how I could do that (using sed or awk)? Many thanks!
Upvotes: 1
Views: 1141
Reputation: 15461
Try this:
$ sed 's~\(.*/\)\([^ ]*\) .*~\1\2 \2~' test.txt
/foo/bar/how how
/foo/bar/are are
/foo/bar/you you
Use the -i
option to edit the file in place:
sed -i 's~\(.*/\)\([^ ]*\) .*~\1\2 \2~' test.txt
Explanation:
s
: substitute \(.*/\)\
: any character up to last /
\([^ ]*\)
: any non-space character followed by a spaceUsing backreference, the strings that matches the pattern are replaced with : first group (/foo/bar/
) followed by repeated second group (the word after last /
: how
, are
or you
).
Upvotes: 1
Reputation: 21965
Below awk
solution might help
awk '{$2=$1;sub(/.*\//,"",$2)}1' test.txt
Ouput
/foo/bar/how how
/foo/bar/are are
/foo/bar/you you
Notes
awk
fields are whitespace separated so, you have two fields ie $1
and $2
.$2=$1
/
using sub(/.*\//,"",$2)
.1
at the end is the simplest of awk
command which prints each record.Upvotes: 2
Reputation: 203655
$ sed 's~\([^/]*\) .*~\1 \1~' file
/foo/bar/how how
/foo/bar/are are
/foo/bar/you you
Upvotes: 2