Visit Jeremy's Blog.
Go Back > Forums > Non-*NIX Forums > Programming
User Name
Programming This forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.


  Search this Thread
Old 02-13-2011, 03:09 PM   #1
LQ Newbie
Registered: Feb 2011
Posts: 17

Rep: Reputation: 0
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?
Old 02-13-2011, 03:31 PM   #2
Nominal Animal
Senior Member
Registered: Dec 2010
Location: Finland
Distribution: Xubuntu, CentOS, LFS
Posts: 1,723
Blog Entries: 3

Rep: Reputation: 944Reputation: 944Reputation: 944Reputation: 944Reputation: 944Reputation: 944Reputation: 944Reputation: 944
The following bash/GNU awk script should solve the problem:
WORK="`mktemp -d`" || exit $?
trap "rm -rf '$WORK'" EXIT
while [ $# -gt 0 ]; do
    shift 1

    if gawk -v "message=the replacement message" '
            { if (length($0) > 10)
                  print message
                  print $0
            }' "$FILE" > "$TEMP" ; then
        if mv -f "$TEMP" "$FILE" ; then
            echo "$FILE: Done." >&2
            echo "$FILE: Cannot replace file." >&2
        echo "$FILE: Error processing file." >&2
        exit 1
    rm -f "$TEMP"
Or, you could just use sed instead, replacing any line with eleven or more characters with Message in file:
sed -e '/^.\{11\}/ s|^.*$|Message|' -i file

Last edited by Nominal Animal; 03-21-2011 at 09:02 AM.


Thread Tools Search this Thread
Search this Thread:

Advanced Search

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off

Similar Threads
Thread Thread Starter Forum Replies Last Post
C++ text file line by line/each line to string/array Dimitris Programming 15 03-11-2008 09:22 AM
script to check the last line in a file is blank line or not naveensankineni Programming 10 03-02-2008 12:13 AM
php - Read file line by line and change a specific line. anrea Programming 2 01-28-2007 02:43 PM
linux scripting help needed read from file line by line exc commands each line read atokad Programming 4 12-26-2003 11:24 PM

All times are GMT -5. The time now is 10:03 PM.

Main Menu
Write for LQ is looking for people interested in writing Editorials, Articles, Reviews, and more. If you'd like to contribute content, let us know.
Main Menu
RSS1  Latest Threads
RSS1  LQ News
Twitter: @linuxquestions
Facebook: linuxquestions Google+: linuxquestions
Open Source Consulting | Domain Registration