繁体   English   中英

sed 插入行命令用新行 OSX 添加文本

[英]sed insert line command to add text with new line OSX

我正在尝试使用 sed 将文本插入到文件的第 100 行,我在其他论坛上找到的语法是:

sed -i '' "100i\ text to insert" filename

当我使用它时,我能够在特定行上添加文本,但它会影响已经存在的其他文本并将其放错位置。

我想在添加到文件的文本之前和之后添加一个新行。

我试过这个sed -i '' "100i\\ text to insert other text to insert" filename但它没有正常工作。

这是我运行上述命令时的输出。 顺序应该是<key>和下面应该是<string>标签。

<key>NSBluetoothAlwaysUsageDescription</key>    <key>NSLocationAlwaysAndWhenInUseUsageDescription</key>
<string>This will allow "App" to find and connect to Bluetooth accessories. This app may also use bluetooth to know when you are nearby.</string>   <string>This app requires constant access to your location in order to track your position, even when the screen is off or the app is in the background.</string>

我似乎无法弄清楚应该在命令中添加什么来添加新行。

我不想打扰订单,我只想在第 100 行插入文本,如果已经有文本,那么该文本应该转到新行。

我使用的是 OSX,这就是为什么我有一个空的 ' ' 作为我的扩展名。

谢谢!

如果你想添加一个换行符,你应该使用: $'\\n' ; ANSI 引用

有关 sed 换行符的更多信息


回答问题; 用:

sed -i '' -e "3s/^//p; 3s/^.*/text to insert/" /tmp/so.txt
  1. 3s/^//p; 重复第 3 行
  2. 3s/^.*/text to insert/"用您的文本替换新的第 3 行

在此处输入图片说明 编辑;

sed -i '' -e "3s/^//p; 3s/^.*/<key>NSBluetoothAlwaysUsageDescription<\/key>/" /tmp/so.txt

记住要转义任何/字符!

如果需要,请尝试 ed(1)。

printf '%s\n' 3a 'text to insert' . w | ed -s file

这里不需要逃避。

printf '%s\n' '100a' '<key>NSBluetoothAlwaysUsageDescription</key>    <key>NSLocationAlwaysAndWhenInUseUsageDescription</key>' '<string>This will allow "App" to find and connect to Bluetooth accessories. This app may also use bluetooth to know when you are nearby.</string>   <string>This app requires constant access to your location in order to track your position, even when the screen is off or the app is in the background.</string>' . w | ed -s file.txt

...或使用 Heredoc

ed -s file.txt <<'EOE'
100a
<key>NSBluetoothAlwaysUsageDescription</key>    <key>NSLocationAlwaysAndWhenInUseUsageDescription</key>
<string>This will allow "App" to find and connect to Bluetooth accessories. This app may also use bluetooth to know when you are nearby.</string>   <string>This app requires constant access to your location in order to track your position, even when the screen is off or the app is in the background.</string>
.
w
EOE

只需将file.txt替换为您的文件名。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM