使用awk替换bash中的文本字符串 [英] Replacing text strings in bash using awk

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

问题描述

我有一个bash文件列表- file1.txt file2.txt file3.txt ,我想另一个包含此字符串但不包含 .txt 的列表,因此

I have a list of files in bash - file1.txt, file2.txt, file3.txt and I would like to make another list that include this strings without .txt, so

names2 = (file1, file2, file3)

然后,我想在文件中找到这些字符串,并在此字符串之前添加一个.请怎么做?

Then, I would like to find these strings in a file and add a before this strings. How to do that please?

我的代码:

names = (file1.txt, file2.txt, file3.txt)

for i in "${names[@]}"; do
    awk '{ gsub("$i","a-$i") }' f.txt > g.txt

f.txt:

TEXT
\connect{file1}
\begin{file2}
\connect{file3}
TEXT 
75

所需的输出 g.txt

TEXT
\connect{a-file1}
\begin{a-file2}
\connect{a-file3}
TEXT 
75

推荐答案

使用sed + printf:

With sed+printf:

$ names=(file1 file2 file3) # Declare array

$ printf 's/%s/a-&/g\n' "${names[@]}" # Generate sed replacement script
s/file1/a-&/g
s/file2/a-&/g
s/file3/a-&/g

$ sed -f <(printf 's/%s/a-&/g\n' "${names[@]}") f.txt
TEXT
\connect{a-file1}
\begin{a-file2}
\connect{a-file3}
TEXT
75

如果您的数组包含后缀.txt,请使用以下命令:

If your array contains .txt suffix, use this:

$ names=(file1.txt file2.txt file3.txt) # Declare array

$ printf 's/%s/a-&/g\n' "${names[@]%.txt}" # Generate sed replacement script
s/file1/a-&/g
s/file2/a-&/g
s/file3/a-&/g

$ sed -f <(printf 's/%s/a-&/g\n' "${names[@]%.txt}") f.txt
TEXT
\connect{a-file1}
\begin{a-file2}
\connect{a-file3}
TEXT
75

如果files列表包含具有重叠字符串的名称,则可以使用单词边界(\<\>)来处理. 例如

If the files list contains the names which have overlapping string, you can use the word boundaries (\<,\>) to handle this. e.g.

$ cat f.txt
TEXT
\connect{file1}
\begin{file2}
\connect{file3file2}
TEXT 
75

$ names=(file1.txt file2.txt file3file2.txt) # Declare array
$ printf 's/\<%s\>/a-&/g\n' "${names[@]%.txt}" # Generate sed replacement script
s/\<file1\>/a-&/g
s/\<file2\>/a-&/g
s/\<file3file2\>/a-&/g

$ sed -f <(printf 's/\<%s\>/a-&/g\n' "${names[@]%.txt}") f.txt
TEXT
\connect{a-file1}
\begin{a-file2}
\connect{a-file3file2}
TEXT 
75

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

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