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


One way:

echo "Linux1_ver2  12542 kernel-update"  |  awk '$1 ~ /^ *Linux1/'
  • $1 and ^ are redundant. Your proposal doesn't cover tabs. – Hauke Laging Apr 17 '13 at 10:40
  • 1
    @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 May 27 '18 at 11: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.


This should work for this specific case.

awk '/^[[:blank:]]*Linux1/ {print}'
  • but if space is before Linux1 the it will no match – yael Apr 17 '13 at 10:27
  • @yael I made an edit to correct that. – Hauke Laging Apr 17 '13 at 10:36
  • +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 May 22 '18 at 4:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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