Take the 2-minute tour ×
Ask Ubuntu is a question and answer site for Ubuntu users and developers. It's 100% free, no registration required.

My string look like this..

foo<.............................. 
bar</............................

I want to pipe for output as

foo
bar

Delete all characters after a first < found each line.

share|improve this question
    
Tried splitting the string by line, then by < and just outputting the first element per line? –  FEichinger Dec 25 '12 at 13:11
    
What have you tried...? This is really something basic. Have a look at the manual page of sed. –  Lekensteyn Dec 25 '12 at 13:12
    
@Lekensteyn I would appreciate if you help me to solve it with sed, I really want to know that one.. Thanks in advance. –  Smile.Hunter Dec 26 '12 at 18:12

2 Answers 2

up vote 2 down vote accepted

This is basic sed. Using sed is not difficult once you know regular expressions. A basic sed command for reading the input and stripping every < and the following part if it exist, then printing the line (may be modified):

$ echo 'foo<....' | sed 's/<.*//'
foo

sed uses regular expressions, the relevant manual page text for sed(1) that applies to the above command:

s/regexp/replacement/
Attempt to match regexp against the pattern space. If successful, replace that portion matched with replacement. The replacement may contain the special character & to refer to that portion of the pattern space which matched, and the special escapes \1 through \9 to refer to the corresponding matching sub-expressions in the regexp

Alternative using cut (manual page for cut(1)), "split the string by < and take the 1st field.

echo 'foo<....' | cut -d'<' -f1

Alternative using grep, "match only everything containing characters of the set a to z (case insensitive)" (manual page of grep(1)):

echo 'foo<....' | grep -io '[a-z]*'

(note: I took the liberty to use [a-z]*, meaning "zero or more occurrences of a letter", because grep won't return an empty line when using the -o option)

Alternative using awk, using the same idea of cut (manual page of awk(1)):

echo 'foo<....' | awk -F '<' '{print $1}'
share|improve this answer

Sample:

cat textWithFooBar.txt | cut -d '<' -f 1 > output.txt

share|improve this answer
2  
Perfect use for cut except for the "Useless use of cat" -- cut -d '<' -f 1 < textWithFooBar.txt > output.txt –  glenn jackman Dec 25 '12 at 17:05

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.