Bash 修改文本文件的精确行号,并在行尾添加特定字符串
给定一个纯文本文件,如何使用bash、awk、sed等在行号NLINE处添加字符串STR,行尾后仅n个空格 因此,例如,如果这是一行NLINE:Bash 修改文本文件的精确行号,并在行尾添加特定字符串,bash,Bash,给定一个纯文本文件,如何使用bash、awk、sed等在行号NLINE处添加字符串STR,行尾后仅n个空格 因此,例如,如果这是一行NLINE: date march 13th 对于5个空间,我们得到 date march 13th STR 一个在新文件中得到修改 谢谢 请注意,APPEND不包含sed可能解释的任何字符。#/bin/bash #!/bin/bash NLINE=10 n=5 string="STR" while read -r line do if (( +
date march 13th
对于5个空间,我们得到
date march 13th STR
一个在新文件中得到修改
谢谢
请注意,APPEND不包含sed可能解释的任何字符。#/bin/bash
#!/bin/bash
NLINE=10
n=5
string="STR"
while read -r line
do
if (( ++count == NLINE ))
then
printf "%s%${n}s%2\n" "$line" " " "$string"
else
echo "$line"
fi
done < inputfile > outputfile
NLINE=10
n=5
string=“STR”
而read-r行
做
如果((++count==NLINE))
然后
printf“%s%${n}s%2\n”“$line”“$string”
其他的
回音“$line”
fi
完成outputfile
可能有助于+1正确处理s
中的双引号。当然,您也可以使用sprintf(“%”“nsp”s“,”)
,以编程方式从大量空间nsp
合成sp
,正如OP所推断的那样,尽管我同意如果OP事先知道有多少空间,那就太过分了。
#!/bin/bash
NLINE=10
n=5
string="STR"
while read -r line
do
if (( ++count == NLINE ))
then
printf "%s%${n}s%2\n" "$line" " " "$string"
else
echo "$line"
fi
done < inputfile > outputfile
NLINE=2
s="somestring"
sp=" "
awk -vn="$NLINE" -vs="$s" -vsp="$sp" 'NR==n{$0=$0 sp s}1' file >temp
mv temp file