subakhan k
subakhan k

Reputation: 35

How to get expected string in linux shell script

I need to delete all line except the string that are with in the character "[ ]".
Input file: ODBC.ini

[ODBC Data Sources]

odbcname     = MyODBC 3.51 Driver DSN
[odbcname]

Driver       = /usr/lib/odbc/libmyodbc.so
Description  = MyODBC 3.51 Driver DSN
[Default]

Expected Output : ODBC.ini

[ODBC Data Sources]

[odbcname]

[Default]

Also need to different dsn names after deleting this old one. Thanks in Advance

Upvotes: 1

Views: 162

Answers (4)

hek2mgl
hek2mgl

Reputation: 158220

You can use awk. The following awk program matches either lines containing a [value in brackets] or empty lines.

awk '/^\[.*]$/ || /^$/' file

Output:

[ODBC Data Sources]

[odbcname]

[Default]

Upvotes: 0

P....
P....

Reputation: 18411

Using grep:

Print the line starting with [ and everything after that till first ] is reached.

 grep -oP '^\[.*?]' infile 
    [ODBC Data Sources]
    [odbcname]
    [Default]

using awk:

awk -F'[|]' '/^\[/{print $1}' infile
[ODBC Data Sources]
[odbcname]
[Default]

Upvotes: 0

Ed Morton
Ed Morton

Reputation: 204548

If this isn't all you need:

$ grep '\[' file
[ODBC Data Sources]
[odbcname]
[Default]

then edit your question to provide more truly representative sample input/output.

Upvotes: 0

heemayl
heemayl

Reputation: 42127

sed with in place (-i) edit:

sed -Ei '/\[[^]]*\]|^[[:blank:]]*$/ !d' ODBC.ini
  • \[[^]]*\] matches the lines that have []

  • ^[[:blank:]]*$ matches blank lines or lines containing only whitespaces

  • !d removes the unmatched lines

Similarly, printing only the matched lines in awk:

awk '/\[[^]]*\]|^[[:blank:]]*$/' ODBC.ini

Recent GNU awk has in place editing option:

awk -i inplace '/\[[^]]*\]|^[[:blank:]]*$/' ODBC.ini

POSIX-ly:

awk '/\[[^]]*\]|^[[:blank:]]*$/' ODBC.ini >ODBC_temp.ini && mv ODBC{_temp,}.ini

Example:

$ sed -E '/\[[^]]*\]|^[[:blank:]]*$/ !d' file.txt
[ODBC Data Sources]

[odbcname]

[Default]


$ awk '/\[[^]]*\]|^[[:blank:]]*$/' file.txt
[ODBC Data Sources]

[odbcname]

[Default]

Upvotes: 1

Related Questions