LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (http://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   [bash - sed - awk] Match line with x characters and add string (http://www.linuxquestions.org/questions/linux-newbie-8/%5Bbash-sed-awk%5D-match-line-with-x-characters-and-add-string-931567/)

TigerClaw 02-27-2012 10:16 AM

[bash - sed - awk] Match line with x characters and add string
 
Hello,

I tried to find a way using the length() function of awk with no success.
I would like to add a string to the beginning or the end of a line that contains less than x character and more than Y characters

Example
Code:

Line:
This line contains less than 100 characters and more than 10
Result:
<string>This line contains less than 100 characters and more than 10
Or
This line contains less than 100 characters and more than 10</string>

Thanks!

Edit: inserted CODE tags

David the H. 02-27-2012 10:27 AM

Please use [code][/code] tags around your code and data, to preserve formatting and to improve readability. Please do not use quote tags, colors, or other fancy formatting.

It might help if you posted your non-working attempts too, so we can help point out where you're going wrong.

Awk can certainly do it, but I'm not going to bother with it right now. I will post a simple bash solution, however.

Code:

x=10
y=100

while read line; do

        ln=${#line}

        if (( ln > x && ln < y )); then
                echo "FOO $line"
        else
                echo "$line"
        fi

done <file.txt


grail 02-27-2012 11:51 AM

Not sure how you could have got stuck??
Code:

awk 'length > 10 && length < 100{print $0,"<string>"}' file
And you can use -v to set variables if required.

TigerClaw 02-27-2012 03:06 PM

Thanks both solutions works perfectly. :)

Sorry if my original question was not formulated in the right way, I'll try to do better next time.

grail 02-28-2012 12:22 AM

Please mark as SOLVED once you have a solution


All times are GMT -5. The time now is 02:21 AM.