Change First Line Of A File Using Bash
Solution 1:
This isn't a bash job, it's a job for ed or sed. For instance, sed -i -e '1s/\\tn0\s*/\t/' -e '1s/\s*\(hilu\)/\n\1/' filename
can do this. As Perl's foundation is a merging of shell, awk and sed, it can also be used similarly.
The editing itself isn't efficient because POSIX file semantics do not permit inserting or removing data, only (over)writing or truncating. This command therefore copies the file, with only the beginning altered. If done as part of a pipeline (just remove -i to output to stdout) it's practically zero cost. Also, with thousands of lines of data that's still pretty small by today's standards.
Solution 2:
Using sed
(with Extended Regex):
sed -r '1s/(.*)\t(hilu.*)/\1\n\2/;1s/\\t[^[:space:]]+//' file
To change the file inplace:
sed -r --in-place '1s/(.*)\t(hilu.*)/\1\n\2/;1s/\\t[^[:space:]]+//' file
Solution 3:
To your example it could be something like this using Python. But also you need to open file and fetch first line inside variable line.
import re
line = 'h\tn0 n1 n2 n3 n4 n5 n6 n7 n8 n9 hilu cjt 1 1000000'
line = re.sub('n9\s*','n9\n', re.sub('h.+n1', 'h\tn1', line))
print line
Post a Comment for "Change First Line Of A File Using Bash"