Reputation: 1403
I'm trying to insert text to the 100th line in a file using sed, and the syntax I've found on other forums is:
sed -i '' "100i\ text to insert" filename
When I use this I am able to add text on a particular line but it affects other text which is already there and misplaces it.
I want to add a new line before and after the text added to the file.
I tried this sed -i '' "100i\ text to insert other text to insert" filename
but it didn't work as excepted.
This is the output when I run the above command. the order should be <key>
and below that should be <string>
tag.
<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>
I can't seem to figure out what should I add in command to add a new line.
I don't want to disturb order I just want if I am inserting text at line 100 and if there is a text already then that text should go to a new line.
I'm using OSX, which is why I have an empty ' ' as my extension.
Thanks!
Upvotes: 1
Views: 1670
Reputation: 7781
Try ed(1) if you want.
printf '%s\n' 3a 'text to insert' . w | ed -s file
Here no escaping needed.
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
... or using a 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
Just replace the file.txt
with your file name.
Upvotes: 0
Reputation: 43884
If you wish to add a newline, you should use: $'\n'
; ANSI quoting
To answer the question; use:
sed -i '' -e "3s/^//p; 3s/^.*/text to insert/" /tmp/so.txt
3s/^//p;
Duplicate line #33s/^.*/text to insert/"
Replace newly line #3 with your textsed -i '' -e "3s/^//p; 3s/^.*/<key>NSBluetoothAlwaysUsageDescription<\/key>/" /tmp/so.txt
Remember to escape any /
chars!
Upvotes: 1