查找和在sed替换从文本文件中多个字符串 [英] find and replace multiple strings from text file in sed
问题描述
以下是与样品和性状的信息,以及测量玩具文本文件。
Below is a toy text file with sample and trait information, and a measurement.
Sample3_trait1 8.5
Sample6_trait2 2.2
Sample7_trait1 9.2
Sample3_trait2 1.3
Sample6_trait1 10.0
Sample7_trait2 2.1
我想的东西更多的信息,以更换样品列,例如样品(例如一个人的名字)的实际名称。这将是 SED
相对容易,如果当时只有3个样品,例如
I would like to replace the sample column with something more informative, like the actual name of the sample (say a persons name). This would be relatively easy in sed
if there were only 3 Samples, e.g.
sed 's/Sample3/john.D/g' file.txt
我可以为每一个样本做到这一点。但我有样品名称的数百或数千。
I could do this for each "sample". But i have 100s or thousands of sample names.
什么ID喜欢做的就是给 SED
有两列的文本文件,原始和替换:
What id like to do is give sed
a text file with two columns, the original and the replacement:
Sample3 john.D
Sample6 mary.D
Sample7 kelly.O
....
Sample1001 amy.P
和任何地方都出现在整个文件中(全球),即徘徊无论样本3被发现,更换john.D。他们代替
And have them replaced wherever they appear throughout the file (globally), i.e., whereever Sample3 is found, replace with john.D.
这是什么,我可以在Bash中循环吗?我可以遍历一列(逐行),但是我不知道该怎么再配列做的。
Is this something that I could do with a loop in Bash? I could loop over a single column (row by row), but Im not sure what to do with matched columns.
任何帮助将是非常美联社preciated。
Any help would be much appreciated.
推荐答案
使用 SED
第二个文件到一个转换 SED
脚本编辑第一:
Use sed
to convert the second file into a sed
script that edits the first:
sed 's/\([^ ]*\) \(.*\)/s%\1_%\2_%/' file.2 > sed.script
sed -f sed.script file.txt
rm -f sed.script
在Bash code无环路。注意 _
的模式;这是来自映射 Sample300
到 john.D00 至prevent
样本3
关键code>。
No loops in the Bash code. Note the _
in the patterns; this is crucial to prevent Sample3
from mapping Sample300
to john.D00
.
如果,你是应该的,你担心中断和脚本的并行运行,则(a)使用 mktemp的
来产生代替文件名 sed.script
,和(b)陷阱中断等,以确保该脚本文件名被删除:
If, as you should be, you are worried about interrupts and concurrent runs of the script, then (a) use mktemp
to generate a file name in place of sed.script
, and (b) trap interrupts etc to make sure the script file name is removed:
tmp=$(mktemp "${TMPDIR:-/tmp}/sed.script.XXXXXX")
trap "rm -f $tmp; exit 1" 0 1 2 3 13 15
sed 's/\([^ ]*\) \(.*\)/s%\1_%\2_%/' file.2 > $tmp
sed -f $tmp file.txt
rm -f $tmp
trap 0
这篇关于查找和在sed替换从文本文件中多个字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!