awk / sed在每行中用行中的前一个字符串替换(Awk/sed replace in each line with previous string in the line)

我有一个像这样的文件test.txt (但包含更多的行)

/foo/bar/how hello /foo/bar/are hello /foo/bar/you hello

我想得到这个输出:

/foo/bar/how how /foo/bar/are are /foo/bar/you you

我试过这个:

while read line do bla=$(echo $line | cut -f4 -d"/" | cut -f1 -d" ") sed -i "s/hello/$bla/" done <test.txt

但是输出结果是:

sed: no input files sed: no input files sed: no input files

当我提供文件名( while read line; do bla=$(echo $line | cut -f4 -d"/" | cut -f1 -d" "); sed -i "s/hello/$bla/" test.txt ; done <test.txt ),我得到这个:

/foo/bar/how how /foo/bar/are how /foo/bar/you how

我想在每一行上用一个出现在同一行上的模式替换一些不变的模式,并且在行之间改变。 任何想法如何我可以做到这一点(使用SEED或AWK)? 非常感谢!

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!

最满意答案

$ sed 's~\([^/]*\) .*~\1 \1~' file /foo/bar/how how /foo/bar/are are /foo/bar/you you $ sed 's~\([^/]*\) .*~\1 \1~' file /foo/bar/how how /foo/bar/are are /foo/bar/you you

更多推荐