LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (http://www.linuxquestions.org/questions/programming-9/)
-   -   access a file line by line, and check the length of each line. (http://www.linuxquestions.org/questions/programming-9/access-a-file-line-by-line-and-check-the-length-of-each-line-862451/)

ddebbie90 02-13-2011 02:09 PM

access a file line by line, and check the length of each line.
 
I want to access a file, and check the length of every line.After, i want to check and replace all lines with length over 10 characters, with a message.Does anyone have a clue on that? :)

Nominal Animal 02-13-2011 02:31 PM

The following bash/GNU awk script should solve the problem:
Code:

#!/bin/bash
WORK="`mktemp -d`" || exit $?
trap "rm -rf '$WORK'" EXIT
while [ $# -gt 0 ]; do
    FILE="$1"
    TEMP="$WORK/temp"
    shift 1

    if gawk -v "message=the replacement message" '
            { if (length($0) > 10)
                  print message
              else
                  print $0
            }' "$FILE" > "$TEMP" ; then
        if mv -f "$TEMP" "$FILE" ; then
            echo "$FILE: Done." >&2
        else
            echo "$FILE: Cannot replace file." >&2
        fi
    else
        echo "$FILE: Error processing file." >&2
        exit 1
    fi
    rm -f "$TEMP"
done

Or, you could just use sed instead, replacing any line with eleven or more characters with Message in file:
Code:

sed -e '/^.\{11\}/ s|^.*$|Message|' -i file


All times are GMT -5. The time now is 08:46 AM.