如何在bash中插入行中特定行和位置的字符

如何在bash中插入行中特定行和位置的字符,bash,char,Bash,Char,我有一个文件,我想在其中的特定行和该行的特定位置添加一个*字符 可能吗 谢谢您可以使用一种外部工具来操作数据,如sed或awk。您可以直接从命令行使用此工具,也可以将其包含在bash脚本中 例如: $ a="This is a test program that will print Hello World! Test programm Finished" $ sed -E '2s/(.{4})/&\*/' <<<"$a" #Or <file #Output

我有一个文件,我想在其中的特定行和该行的特定位置添加一个*字符

可能吗


谢谢

您可以使用一种外部工具来操作数据,如sed或awk。您可以直接从命令行使用此工具,也可以将其包含在bash脚本中

例如:

$ a="This is a test program that will print
Hello World!
Test programm Finished" 
$ sed -E '2s/(.{4})/&\*/' <<<"$a"   #Or <file
#Output:
This is a test program that will print                                                                                                                                          
Hell*o World!                                                                                                                                                                   
Test programm Finished
在pure bash中,您可以通过以下方式实现上述输出:

while read -r line;do
  let ++c
  [[ $c == 2 ]] && printf '%s*%s\n' "${line:0:4}" "${line:4}" || printf '%s\n' "${line}"
  # alternative: 
  # [[ $c == 2 ]] && echo "${line:0:4}*${line:4}" || echo "${line}"  
done <<<"$a"
#Alternative for file read:
# done <file >newfile

我建议使用
sed
。如果要在第5列的第2行插入星号:

sed -r "2s/^(.{5})(.*)$/\1*\2/" myfile.txt
2s
表示您将在第二行执行替换
^(.{5})(.*)$
表示从行首开始提取5个字符,并在行尾提取所有字符
\1*\2
表示您是从第一个匹配项(即5个起始字符)然后是一个
*
然后是第二个匹配项(即直到行尾的字符)生成字符串

如果行和列在变量中,则可以执行以下操作:

_line=5
_column=2
sed -r "${_line}s/^(.{${_column}})(.*)$/\1*\2/" myfile.txt

你可以使用子字符串:是的,它是可能的使用子字符串只适用于一行,对吗?如何更改(添加字符)测试文件中的特定行?@DCuser欢迎。我还将尝试包含纯bash解决方案。@DCuser添加了纯bash解决方案。但此方法仅打印修改后的行,它不会替换包含该行的文件的内容……对吗?@DCuser您可以使用
sed-I
替换文件的内容-我指的是文件的就地编辑。对于bash解决方案,您需要应用
>newfile
sed -r "2s/^(.{5})(.*)$/\1*\2/" myfile.txt
_line=5
_column=2
sed -r "${_line}s/^(.{${_column}})(.*)$/\1*\2/" myfile.txt