Shell—File content manipulation

Read each line of the file and output

#!/bin/bash

# 方法1
while read line
do
    echo $line
done < a.txt


# 方法2
cat a.txt | while read line
do
    echo $line
done

# 方法3
# for line in `cat  a.txt`
for line in $(cat a.txt)
do
    echo $line
done

File content sorting tools sort and uniq

sort: sort is a tool for sorting the contents of files in units of rows, and can also be sorted according to different data types.

Usage: sort [options] parameter

  • -n: sort by number
  • -r: reverse sort
  • -u: equivalent to uniq, which means that only one line of the same data is displayed
  • -f: Ignore case -b: Ignore the space in front of each line -M: Sort by month
  • -t: Specify the delimiter, and use the Tab key to separate by default -o <output file>: dump the sorted results to the specified file -k: specify the sort area
[root@localhost ~]# sort /etc/passwd
[root@localhost ~]# sort -r /etc/passwd

uniq: Remove duplicate rows and count the number of occurrences of each row (adjacent rows). The uniq tool is usually used in conjunction with the sort command to report or ignore duplicate lines in a file.

Usage: uniq [options] parameters

  • -c: count
  • -d: Only display duplicate rows (here, duplicate rows are limited to adjacent rows. If there are two duplicate rows but not adjacent, it is not satisfied)
  • -u: only display lines that appear once
[root@localhost ~]# uniq -c test.txt 
[root@localhost ~]# uniq -u test.txt 
[root@localhost ~]# sort -n test.txt | uniq -c # Delete the test.txt file Repeat the line, and count the number of repetitions of the line 

[root@localhost ~]# sort -n test.txt | awk'{if($0!=line)print; line=$0}' 
[root@localhost ~]# sort -n test.txt | sed'$!N; /^\(.*\)\n\1$/!P; D'

Count the number of lines, words, and bytes of the file, and display and output the statistical results

[root@localhost ~]# wc -l /etc/passwd # count the number of lines in the file (the number of lines in the content) 
[root@localhost ~]# wc -c /etc/passwd # count the number of bytes in the file 
[root @localhost ~]# wc -m /etc/passwd # Count the number of characters in the file 
[root@localhost ~]# wc -w /etc/passwd # Count the number of occurrences of words 
[root@localhost ~]# wc-lcw file1 file2 
[ root@localhost ~]# ls -l | wc -l # Used to count the number of files in the current directory

  

Guess you like

Origin blog.csdn.net/qq_45533841/article/details/112470907