4

I want to grep name from package.json. My file looks like below. Name is in second line of the file.

 {
  "name": "Proje",
  "version": "1.0.0",

Output should be only Proje

4
  • 3
    Why grep specifically? there are much more robust ways of extracting elements from json e.g. jq -r '.name' package.json Nov 8, 2018 at 3:05
  • This method is working. Thanks a lot. But I need a shell script. Is there a accurate way to do it by using shell commands? I used this command and It shows the required output.grep -ri "name" package.json |head -n 1 | cut -c 12-16
    – Janith
    Nov 8, 2018 at 3:10
  • 2
    JSON is sufficiently complex to require a proper parser, like XML, CSV, YAML, ... Nov 8, 2018 at 3:54
  • 1
    Suppose your package.json looked like { (newline) "version": "0.1.name", (newline) "name": "Proj", ... , then the grep solution is broken because the first "name" appears in an unexpected place.. Nov 8, 2018 at 3:56

3 Answers 3

2

Assuming the input file is exactly the format shown; pure POSIX shell, no external utils:

while read a b ; do 
    [ "$a" = '"name":' ] && { b="${b%\"*}" ; echo "${b#\"}" ; break ; }
done < package.json

Output:

Proje
1
  • Thank you so much above command is working properly
    – Janith
    Nov 8, 2018 at 4:51
2

This line will extract the string value of name in package.json

cat package.json | grep "name" | cut -d':' -f 2 | cut -d'"' -f 2

example:

Hello-Kittys-MBP app-build % cat package.json | grep "name"
  "name": "@itential/app-build",

Hello-Kittys-MBP app-build % cat package.json | grep "name" | cut -d'"' -f 4
@itential/app-build
2
  • What if the name contains :?
    – Kusalananda
    Feb 21, 2022 at 21:15
  • here is another try one of my co-workers came up with: grep -o '"name": "[^"]*' package.json | grep -o '[^"]*$'
    – Zack S
    Feb 22, 2022 at 19:26
1

I used below commands to accessing package.json file and extract the name and also the version. All are working and thank you so much for your support.

grep -ri "name" package.json |head -n 1 | cut -c 12-16 

cat package.json | grep name | head -1 | awk -F: '{ print $2 }' | sed 's/[ ",]//g' 

node -p "require('./package.json').name" 

while read a b ; do
   [ "$a" = '"name":' ] && { b="${b%\"*}" ; echo "${b#\"}" ; break ; }
done < package.json

jq -r '.name' package.json 
2
  • The code cat package.json | grep name | head -1 can be simplified to just grep -m1 name package.json
    – agc
    Nov 8, 2018 at 5:02
  • @agc grep -m1 name package.json | awk -F: '{ print $2 }' | sed 's/[ ",]//g' yes It also working. Thank you so much
    – Janith
    Nov 8, 2018 at 5:36

You must log in to answer this question.

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