39

how to print the line in case the first field start with Linux1

for example:

  echo Linux1_ver2  12542 kernel-update  |   awk '{if ($1 ~ Linux1 ) print $0;}'

the target is to print the line , while the first field start with Linux1

example of lines:

Linux1-new  36352 Version:true
Linux1-1625543  9847
Linux1:16254 8467563 

remark - space or TAB could be before the first filed

3 Answers 3

46

awk ignores leading blanks when assigning fields. The default command is print.

awk '$1 ~ /^Linux1/'

Is what you want.

Detailed explanation:

  • $1 tells awk to look at the first "column".
  • ~ tells awk to do a RegularExpression match /..../ is a Regular expression.
  • Within the RE is the string Linux and the special character ^.
  • ^ causes the RE to match from the start (as opposed to matching anywhere in the line).

Seen together: Awk will match a regular expression with "Linux" at the start of the first column.

23

One way:

echo "Linux1_ver2  12542 kernel-update"  |  awk '$1 ~ /^ *Linux1/'
2
  • $1 and ^ are redundant. Your proposal doesn't cover tabs. Commented Apr 17, 2013 at 10:40
  • 4
    @HuakeLaging Why do you think the $1 and ^ are redundant? I am quite sure both are required so that the first word is matched against only, and so that the match is anchored at the start (e.g., "mLinux" could be matched by /Linux1/, but not by /^Linux/).
    – Nick Bull
    Commented May 27, 2018 at 11:46
3

This should work for this specific case.

awk '/^[[:blank:]]*Linux1/ {print}'
3
  • but if space is before Linux1 the it will no match
    – yael
    Commented Apr 17, 2013 at 10:27
  • @yael I made an edit to correct that. Commented Apr 17, 2013 at 10:36
  • 1
    +1 To anyone wondering what this syntax is doing: it's saying "do the things inside the braces only if the regex matches that line".
    – user541686
    Commented May 22, 2018 at 4:46

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .