Editing Every 10th Line of a File
Hi,
I am trying to replace the first word of every 10th line in a file. What would be the most efficient language to do this. Thanks. |
Quote:
If you mean just a small-ish text file, replacing something like "string1" with "string2", bash would work fine. If you're talking about a 20GB file, and replacing strings like "Item-A13802-CL" with "ItemBCL13802", that's more of a job for Perl, or another more heavy-duty language. |
Hi.
GNU sed has a feature that allows firstline-step addresses, like so: Code:
#!/usr/bin/env bash Code:
% ./s1 ( edit 1: forgot option "-r" ) |
1) Make sure you think of a string that is NOT present in the file. For example, "WOOTWOOT".
2) Add line number and "WOOTWOOT" before every line: Code:
% nl -s " WOOTWOOT " file.txt > tempfile1.txt Code:
% less tempfile1.txt Code:
% sed 's/[0-9]*0 WOOTWOOT /s/find this string/replace with this string/' tempfile1.txt > tempfile2.txt Code:
% sed 's/^.*WOOTWOOT //' tempfile2.txt > tempfile1.txt Code:
% mv tempfile1.txt file.txt |
Code:
perl -i.bak -pe '$_=~s/\s*(\w+)/Word Replacement/ if $.=~/0$/' file (edit) added \s just in case there are some space chars before the first word |
All times are GMT -5. The time now is 10:35 AM. |