Dealing with Text Files in Linux


Some common commands are introduced for editing files in Linux.

1. Replace all in a text file:
# sed -i 's/old-word/new-word/g' *.txt

2. Display all lines containing some keyword in a text file:
# cat 'file' | grep 'word'

3. Count number of lines in a text file:
# cat 'file' | wc

4. Find a set of file that contain some key word:
# find . -type f -name 'file-name' -exec grep -ls 'key-word' {} \;

5. Display first c lines of a file:
# head -n'c' 'file'

6. Display last c lines of a file:
# tail -n'c' 'file'

7. Display substrings between position n and m in each line:
# cut -c 'n'-'m' 'file'

8. Display cth column of each line deliminated by space:
# cut -d " " -f'c' 'file'

9. Display nth line of a file:
# cat 'file' | sed -n 'n'p

10. Display a range of lines of a file:
# cat 'file' | sed -n -e 'i,jp;m,np'

11. Display all lines not containing some keyword in a text file:
# cat 'file' | grep -v 'word'

12. Append a set of input files by columns separated by a tab:
# paste 'file1' 'file2' ... 'filen' > 'file.out'

13. Append a file to another file:
# cat 'file1' >> 'file2'