Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash get first N non white space characters

Tags:

regex

macos

sed

awk

I am trying to check if a certain line in a file is commented out (has // as the first non white space characters of the line). How can I do this in bash? I'm ok with using sed, awk, whatever as long as it comes standard on OS X.

I have tried:

grep textOnlyOnMyLine | cut -c 1-2 myFile.java

but this will pick up white spaces if white spaces are the first 2 characters of the line. Also this command seems to hang after outputting what it finds.

like image 412
Adam Johns Avatar asked Feb 11 '26 23:02

Adam Johns


2 Answers

You can use grep:

grep '^[[:blank:]]*//' *.java

To search for a particular line # you can use sed:

sed -n '3s|^[[:blank:]]*//|&|p' file
like image 130
anubhava Avatar answered Feb 13 '26 14:02

anubhava


With awk you can get the lines that are comments with:

awk '/\s*\/\//' file

So it looks for [spaces] plus // in the line and then prints them.

In case you want to check a specifid word you can do:

awk '/\s*\/\// && NR==line_number' file

Test

$ cat a
hello
// this is a coment
 // this is a coment

$ awk '/\s*\/\//' a
// this is a coment
 // this is a coment

$ awk '/\s*\/\// && NR==1' a
$

$ awk '/\s*\/\// && NR==2' a
// this is a coment
like image 36
fedorqui 'SO stop harming' Avatar answered Feb 13 '26 13:02

fedorqui 'SO stop harming'



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!