Home
Thursday, September 21, 2017
3:09:36 PM
Users online: 0   You are here >> Home > Programming

Forums | Programming Forums search
Forum FAQ
   
  1  
A few quick bash scripting questions...
njbignell 
7/9/08 1:25:32 PM
Overlord
I have a few quick questions that I couldn't find the answer to on Google:

How do I delete a line from a text file if it begins with a certain string?

How do I validate a variable using regular expression in an if statement?

Thanks in advance

-----

freespace 
7/9/08 2:53:15 PM
Hero
Titan


man sed


If you are really lazy, see below


---BEGIN SPOILER

sed -i '/^string//g' file


---END SPOILER



Edited by freespace: 7/9/2008 2:54:09 PM

-----
By perseverance the snail reached the ark.

http://www.shuningbian.net - blog
http://anonshare.pictorii.com - share files anonymously
http://dailydiscovery.b3ta.org - learn something new
its f reespace damn it!

njbignell 
7/9/08 3:42:12 PM
Overlord
I've come up with this for validating input but it always says it's invalid:

echo -e "Enter Phone Number: \c"
read add_1
if [[ ! $add_1 =~ ^\d{5,12}$ ]]
then
echo "error: invalid input"
add
fi

-----

eckythump 
9/9/08 5:11:48 AM
Champion

To delete lines starting with a string:
sed -i '/^string/d' filename
The -i flag edits the file inplace. You may want to leave it out while you test.

For regex if statements:
if echo string-to-match-against | grep -Eq '^holy.*crap[abc123]itsare..x$';then 
echo true
else
echo false
fi
Note the -E. If you want perl-style regex, use the -P flag instead.

% if echo 1235 |grep -Pq '^\d{5,12}$';then echo true;fi 
% if echo 12345 |grep -Pq '^\d{5,12}$';then echo true;fi
true
% if echo 123454444444 |grep -Pq '^\d{5,12}$';then echo true;fi
true
% if echo 1234544444444 |grep -Pq '^\d{5,12}$';then echo true;fi
%




Edited by eckythump: 9/9/2008 05:18:52 AM

-----
My mind is a swirling miasma of scintillating thoughts and turgid ideas.

njbignell 
9/9/08 12:57:11 PM
Overlord
Thanks, was missing the -i flag for the sed command. I found that you can use =~ in an if conditional to test a string against regex but I could only get it working on integers so I'll use your grep idea.

Thanks, huge help

-----

eckythump 
9/9/08 3:12:12 PM
Champion

Welcome.

the echo | grep approach is probably better, anyway, as it's more portable and not limited to bash 3.x+

And I don't think regex really has any comprehension of integer vs. floating point numbers. \d is basically just a synonym for [0-9] (I believe/assume.)

-----
My mind is a swirling miasma of scintillating thoughts and turgid ideas.

  1  
Forums | Programming