awk替换行中的字符串 [英] Awk replace string in line

查看:545
本文介绍了awk替换行中的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

注意: 这个问题看起来像是先前发布的一个,但正如评论中提到的,它原来是一个

NOTE: This question looks like a previously posted one, but as mentioned in the comments, it turned out to be a chameleon question. I accepted the answer, and I'm posting here the same problem but with slightly different "solution conditions".

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

I have a file test.txt like this (but containing many more lines)

/foo/bar/how /SOME_TEXT_HERE/hello
/foo/bar/are hello/SOME_OTHER_TEXT
/foo/bar/you hello

我想得到这个输出:

/foo/bar/how /SOME_TEXT_HERE/how
/foo/bar/are are/SOME_OTHER_TEXT
/foo/bar/you you

我已经尝试过了:

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 /SOME_TEXT_HERE/how
/foo/bar/are how/SOME_OTHER_TEXT
/foo/bar/you how

注意:

我希望解决方案:

  1. 允许我定义一个变量(此处为bla),该变量将由我手动定义,并且与一个文件不同(因此不使用诸如基本字段位置之类的sthg),而是使用cut或其他命令,例如我的示例)

  1. allow me to define a variable (here, bla) that I will define manually and differently from one file to the other (so not using sthg like basic field position), but using cut or other command as in my example)

通过此变量在行中的其他位置替换特定的字符串(因此不是像$2这样的字段位置,而实际上是像s/hello/$bla这样的字段)

replace a specific string somewhere else in the line by this variable (so not a field position like $2, but really something like s/hello/$bla)

虽然我不确定这是否可能(显然我自己不知道如何做到这一点...),但是感谢您的宝贵时间! :)

I'm not sure of this is possible though (obviously I don't know how to do this by myself...), but thanks for your time trying! :)

推荐答案

awk '{sub(/are hello/,"are are")sub(/you hello/,"you you")}1' file

/foo/bar/how /SOME_TEXT_HERE/hello
/foo/bar/are are/SOME_OTHER_TEXT
/foo/bar/you you

这篇关于awk替换行中的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆