Longest line in a file

前端 未结 14 1976
鱼传尺愫
鱼传尺愫 2020-11-27 10:34

I\'m looking for a simple way to find the length of the longest line in a file. Ideally, it would be a simple bash shell command instead of a script.

相关标签:
14条回答
  • 2020-11-27 11:07

    Just for fun and educational purpose, the pure POSIX shell solution, without useless use of cat and no forking to external commands. Takes filename as first argument:

    #!/bin/sh
    
    MAX=0 IFS=
    while read -r line; do
      if [ ${#line} -gt $MAX ]; then MAX=${#line}; fi
    done < "$1"
    printf "$MAX\n"
    
    0 讨论(0)
  • 2020-11-27 11:08

    If you are using MacOS and are getting this error: wc: illegal option -- L you dont need to install GNU sipmly do this.

    If all you want to do is just get the count of the characters in the longest line of the file and you are using OS X run:

    awk '{print length}' "$file_name" | sort -rn | head -1

    Something like this;

    echo "The longest line in the file $file_name has $(awk '{print length}' "$file_name" | sort -rn | head -1) characters"

    Outputs:

    The longest line in the file my_file has 117 characters

    0 讨论(0)
  • 2020-11-27 11:10

    Using wc (GNU coreutils) 7.4:

    wc -L filename
    

    gives:

    101 filename
    
    0 讨论(0)
  • 2020-11-27 11:10
    awk '{print length, $0}' Input_file |sort -nr|head -1
    

    For reference : Finding the longest line in a file

    0 讨论(0)
  • 2020-11-27 11:10
    awk '{ if (length($0) > max) {max = length($0); maxline = $0} } END { print maxline }'  YOURFILE 
    
    0 讨论(0)
  • 2020-11-27 11:10

    Variation on the theme.

    This one will show all lines having the length of the longest line found in the file, retaining the order they appear in the source.

    FILE=myfile grep `tr -c "\n" "." < $FILE | sort | tail -1` $FILE
    

    So myfile

    x
    mn
    xyz
    123
    abc
    

    will give

    xyz
    123
    abc
    
    0 讨论(0)
提交回复
热议问题