逐行替换与另一个文件中的内容

时间:2017-03-17 16:08:30

标签: bash sed

我正在自动执行某些任务。

我想知道是否有可能从中间的不同文件替换每一行 将需要指导者和源文件中的日期

每一行的结构都是

blahblahblah....string_I_need_to_replace....blahblahblah

我使用sed命令提取我需要替换的字符串,因为它需要从data1,data2,data3,转到data1-description; data2 - description; data3 - description

data1,data2,data3并非始终相同,只保证data1在行中

这一行

blahblah....mentor will be required.",Collaboration,Analytical Skills,Integrity & Ethics,3/1/17 20:04 ... blahblah

需要

blahblah....mentor will be required.","Collaboration-description;Analytical Skills - description; Integrity & Ethics - description " 3/1/17 20:04 ....blah blah blah

在我的解析文件的第一行包含

Collaboration-description;Analytical Skills - description; Integrity & Ethics - description 

我使用sed命令在单独的文件中提取每行的内部部分Collaboration-description;Analytical Skills - description; Integrity & Ethics - description

在我有兴趣更改的数据之前和之后有很多,;和数字,并且计数因行而异,所以替换第n个,这将是一个问题三,当data2和data3为空时,outfile2outfile3处理最后删除的原因

#!/bin/bash
unset LANG
cat export-14.csv | sed -n -e 's/^.*mentor will be required.",//p' > outfile
sed 's/[0-9].*//'  outfile > outfile2
sed 's/,$//'       outfile2 > outfile3
sed 's/,$//'       outfile3 > outfile4
sed 's/,/;/g'      outfile4 >outfile5
sed 's/Analytical SKills/Analytical Skills - identifying and solving problems/' outfile5 > outfile6
sed 's/Adaptability/Adaptability - embracing opportunities for improvement and resilience/' outfile6 > outfile7
sed 's/Collaboration/Collaboration - working with others/' outfile7 > outfile8
sed 's/Technology/Technology - employing current and emerging software\/tools/' outfile8 > outfile9
sed "s/Communication/Communication - articulating one\'s self/g" outfile9 > outfile10

1 个答案:

答案 0 :(得分:2)

您的问题I would like to know if it is possible to substitute each line from a different file in between mentor will be required and the date in the source file的答案是,但没有简洁,可测试的样本输入和预期输出,这些信息的确可以提供尽可能多的信息。

话虽如此 - 您当前的一系列sed脚本可以重写为单个awk脚本:

awk 'sub(/^.*mentor will be required.",/,"") {
    sub(/,{1,2}[0-9].*/,"")
    gsub(/,/,";")
    sub(/Analytical SKills/,"Analytical Skills - identifying and solving problems")
    sub(/Adaptability/,"Adaptability - embracing opportunities for improvement and resilience")
    sub(/Collaboration/,"Collaboration - working with others")
    sub(/Technology/,"Technology - employing current and emerging software/tools")
    sub(/Communication/,"Communication - articulating one\047s self")
}' export-14.csv > outfile10

无论你想做什么,这都是一个更好的起点。