Tag Info

New answers tagged

1

If I correctly understood your question you are looking for sed 's/\(pattern {[^}]*}\)/\1;/g' where \1 replaces everything what matched inside \(...\). The output: hello {sdsdsdsds} pattern {askjdasjkdjasd}; hello {siadsd} pattern {iuewer};


1

login shell: A login shell logs you into the system as a spiecified user, necessary for this is a username and password. When you hit ctrl+alt+F1 to login into a virtual terminal you get after successful login: a login shell (that is interactive). Sourced files: /etc/profile and ~/.profile for Bourne compatible shells (and /etc/profile.d/*) ...


0

You can use newline \n together with carriage return \r. I don't have BSD sed at hand to test, but it works with GNU sed. $ var=Dot $ lol=$(echo $var | sed 's/Dot/Dot\n\r/g') $ echo "$lol" Dot $ If BSD sed doesn't support \r then another (rather ugly) solution is to print \n\r with echo -e or printf: lol=$(echo $var | sed "s/Dot/Dot\\$(printf ...


0

Shell removes the trailing newlines. The common workaround is to add a character at the very end in the command substitution, and then remove it. x=$( echo a; echo ; echo :) echo "${x%:}"


1

Note that when you use ls with a pipe, the files are output a-line-at-a-time, allowing you to use grep and other filters; hence the following will work independently of the shell used (but will generate files on separate lines). ls | egrep "foo(uubar|)\.txt" If you want the columns back: ls | egrep "foo(uubar|)\.txt" | column


2

Here's a solution that works with tcsh. I'd use a brace expansion operator, {..}, like so: $ echo foo{,uubar}.txt foo.txt foouubar.txt This works by making a set of sub-strings that the string "foo" is alternatively added to. In this case we're using {,...} which means the first sub-string tried is nothing. The second sub-string is "uubar". References ...


0

If the install command is quoted by backticks, and the line is split by newline as posted. An example: msg='Message: Please install the vagrant-vbguest plugin by\nrunning `vagrant plugin install vagrant-vbguest`' status=$( vagrant up ) cmd=$( echo "$status" | grep -o "by\nrunning \`[a-z \-]*" | cut -d"\`" -f 2 ) OR cmd=$( echo "$msg" | cut -d"\`" -f 2 ...


-1

There are some complicated answers, giving a lot of interesting details for the geeks among us, but it's really quite simple - processing a large file in a shell loop is just too slow. I think the questioner is interesting in a typical kind of shell script, which may start with some command-line parsing, environment setting, checking files and directories, ...


3

Non-recursive Probably the simplest version if you don't need recursivity : wc -l /group/book/four/word/*|sort -n wc counts lines (option -l) in every (but hidden) (*) files under /group/book/four/word/, and sort sorts the result (through the pipe |) numerically (option -n). Recursive Someone made a comment to this answer mentioning grep -rlc, before ...


1

zsh's jobs builtin can change the shell's process name. jobs -Z newname


1

You could make your script recursive this way: #! /bin/sh - do-something-with "$1" shift [ "$#" -eq 0 ] || exec "$0" "$@" Then when running your-script a b c, the ps output would show in turn: your-script a b c your-script a b your-script a


3

With ksh or bash (or zsh): cd() { builtin cd "$@" || return [ "$OLDPWD" = "$PWD" ] || case $PWD in (*/public_html) echo do something esac } With zsh: chpwd() case $PWD in (*/public_html) echo do something esac (chpwd is a hook function that is called whenever the current working directory changes (by way of cd, pushd, popd...)).


4

Digging around here, I understood from http://unix.stackexchange.com/a/56877/54067 (where both the question and answer are worded differently and the problem is not related to interactive input) that the reason for the problem is that the cp -i expects the user to give the interactive input confirmation via stdin but in the cat | while read loop stdin is ...


0

To complement the other answers, zsh, fish and (t)csh are more helpful here in that they can help you show your mistake before it becomes a problem: If there's no *test.txt file in the current directory: zsh$ find . -name *test.txt zsh: no matches found: *test.txt fish> find . -name *test.txt fish: No matches for wildcard '*test.txt'. find . -name ...


3

You don't specify whether you also want the files in any subdirectories of /group/book/four/word. The find solution in jherran's answer will descend into subdirectories. If that is not wanted, use the shell instead: for file in ./*; do [ -f "$file" ] && wc -l "$file"; done | sort -n If your file names can contain newlines, you can use something ...


4

You could add this function to your .bashrc or other startup file (depending on your shell). Hope this helps. cd() { if [ "$1" = "public_html" ]; then echo "current dir is my dir" fi builtin cd "$1" }


3

With zsh: lines() REPLY=$(wc -l < $REPLY) printf '%s\n' /group/book/four/word/*(.no+lines) We define a new sorting function lines that replies with the number of lines in the file. And we use the o+lines glob qualifier which together with n (for numeric sort), defines how the results of the glob are ordered. (. also added to only check regular files). ...


8

You should use a command like this: find /group/book/four/word/ -type f -exec wc -l {} + | sort -rn find : search for files on the path you want. If you don't want it recursive, and your find implementation supports it, you should add -maxdepth 1 just before the -exec option. exec : tells the command to execute wc -l on every file. sort -rn : sort the ...


8

I put this as an answer, because cannot format it in the comment properly foo() { echo foo echo bar } > foo foo bar Imho, you have more freedom with a function than with alias. At least you can format it properly. Advanced Bash-Scripting Guide In a script, aliases have very limited usefulness. It would be nice if aliases could assume some ...


5

start cmd:> alias foo="echo foo; echo bar" start cmd:> foo foo bar


1

Use the shell's suffix removal feature str=/opt/oracle/app/oracle/product/12.1.0/bin/tnslsnr path=${str%/*} echo "$path" In general, ${parameter%word} removes word from the end of parameter. In our case, we want to remove the final slash and all characters which follow: /*. The above produces: /opt/oracle/app/oracle/product/12.1.0/bin Use dirname ...


0

start cmd:> dirname "/opt/oracle/app/oracle/product/12.1.0/bin/tnslsnr" /opt/oracle/app/oracle/product/12.1.0/bin file_path="/opt/oracle/app/oracle/product/12.1.0/bin/tnslsnr" dir_path_woslash="${file_path%/*}" echo "$dir_path_woslash" /opt/oracle/app/oracle/product/12.1.0/bin shopt -s extglob dir_path_wslash="${file_path%%+([^/])}" echo ...


2

You should always avoid mixing languages as much as possible. In this case you are trying to mix shell script into ruby script. Mixing languages convolutes your code and makes it fragile. The solution in this case is to use ruby's native environment variable support. $ GHREPO=ecx ruby -rjson -e 'j = JSON.parse($stdin.read); puts ...


1

Simply you can sort it by using sort command sort -r version.log | head -n1 | awk '{print $2}' Output: /opt/oracle/app/oracle/product/12.1.0


4

You can do it with AWK. $ awk '{if(max<$1){max=$1;line=$2}}END{print line}' file /opt/oracle/app/oracle/product/12.1.0 Here first column of each line is compared with the variable max (which is initially 0). If the first column has a value greated that max then the second column is stored in the variable line, this continues for each and every line of ...


2

sort -k1 -n filename | tail -1 | awk '{print $2}'


2

awk '$1 > max { max = $1; output = $2 } END { print output }' version.log


-2

This should work: awk -v max=0 '{if($1>max){want=$2; max=$1}}END{print want} ' version.log The -v max=0 sets the variable max to 0, then, for each line, the first field is compared to the current value of max. If it is greater, max is set to the value of the 1st field and want is set to the current line. When the program has processed the entire file, ...


0

It should be '"'$GHREPO'"' so the command is cat dummy.json | ruby -rjson -e 'j = JSON.parse($stdin.read); puts j["ChgSub"]['"'$GHREPO'"'][0]["Major"].to_s' @Etan was pretty close to the answer.


1

tl;dr version You are passing a string literal to the command/program, just like double-quotes but differ that single-quotes prevent variable and wildcard expansion while double-quotes expand them in to the string literal. Example: $ export MY_VAR=my_string $ echo "$MY_VAR" my_string $ echo '$MY_VAR' $MY_VAR The same applies to wildcards Hope it helps. ...


-4

In the first case, the argument *test.txt is considered an operator of the find command itself whereas with quotes, the argument *test.txt will be considered a parameter to a switch of find. If you have more than one text files with the .txt extension in your current directory, the following will fail as find will not see a *.txt argument: find . -name ...


20

The quotes protect the contents from shell wildcard expansion. Run that command (or even simpler just echo *test.txt in a directory with a footest.txt file and then one without any files that end in test.txt and you will see the difference. $ ls a b c d e $ echo *test.txt *test.txt $ touch footest.txt $ echo *test.txt footest.txt The same thing will ...


3

Variables don't get evaluated in a single quoted string. You need to use double quotes. If you can't or don't want to use double quotes for the whole string you can use them for just that part of the string. ruby -rjson -e 'j = JSON.parse($stdin.read); puts j["ChgSub"]["'"$GHREPO"'"][0]["Major"].to_s' That is three separate quoted strings next to one ...


2

You can compile this c++ code for quite quick results. It completes in around 0.19 - 0.27 seconds on a 1000 line file. It currently reads 10000 lines into memory(to speed up printing to screen) which if you had 1000 characters per line would use less than 10mb memory which i wouldn't think would be a problem. You can remove that section completely though ...


0

You should be using -exec here: find . \( -name '*.mp4' -o -name '*.mkv' -o -name '*.avi' \) \ -exec sh -cf 'IFS=._ for f do d=${f%/*} f=${f##*/} [ -n "${f##*_*}" ] && continue set -- $f printf "%s\n" "mv \\" "$d/$f \\" "$d/$*" done' find.rename.shc {} + As written this only prints the command it will execute if you go ...


-1

I'm pretty sure you're looking for join. Unfortunately, I'm not very good with it. I know there's a way to make it fill the fields the way you want as well, but so far I can only get the unpaired lines to print at the head of the line. join only joins two files at a time, and so the unpaired lines don't show where you want - at least, I think they don't. ...


2

#!/bin/bash unset u mnt() { ${u+u}mount /ip/share1 ${u-"/local/share1"}; } case "$1" in (-mount) :;; (-umount) u= ;; (-restart) u= mnt ;; (*) ! :;; esac && mnt You could use a function as ^above^.


3

It looks to me like that should work, other than the syntactical quibble of missing )s. I tested this and it behaves correctly.. #/bin/bash case "$1" in "-mount") mount /path/to/device /path/to/mountpoint ;; "-unmount") umount /path/to/mountpoint ;; "-mount") "$0" -unmount "$0" -remount ;; *) echo "You have failed to ...


0

What you want to do requires a little programming: #!/usr/bin/perl # Program to join files of TAB separated data based on first key # --J. Ziobro--: 11/2014 use strict; my $f; my %allLines; my $maxColumns = 0; my $fileNum = 0; my %keys; foreach $f (@ARGV) { die "Could not open $f" unless open( F, $f ); while (<F>) { chop; my ...


1

You have to use backticks (`) instead of fancy quotes (‘). wget --output-document=camera_3`date +%Y-%m-%d_%H:%M:%S`.jpg [IP]/image.jpg Or better yet use the sub command notation, $(...). wget --output-document=camera_3$(date +%Y-%m-%d_%H:%M:%S).jpg [IP]/image.jpg Additionally you can simply the formatting to date like so: wget ...


0

$? gives you the status of last executed command:called as exit status if success its 0 else can be any number root@hackaholic:~# echo "hello" hello root@hackaholic:~# echo $? 0 root@hackaholic:~# ps PID TTY TIME CMD 21005 pts/2 00:00:00 bash 21051 pts/2 00:00:00 ps root@hackaholic:~# echo $? 0 root@hackaholic:~# junk bash: junk: command not ...


41

Yes, we see a number of things like: while read line; do echo $line | cut -c3 done Or worse: for line in `cat file`; do foo=`echo $line | awk '{print $2}'` echo whatever $foo done (don't laugh, I've seen many of those). Generally from shell scripting beginners. Those are naive literal translations of what you would do in imperative languages ...


2

Instead of modifying the init script, investigate what debugging options are already provided with the software. You have not specified what Linux distribution you're using. However, I can suggest the following based on CentOS 6: 1: the man page for named shows these debug options for the named daemon: -d debug-level Set the daemon’s debug ...


1

Using Python’s standard library: >>> ipaddress.ip_address('192.168.1.1').reverse_pointer '1.1.168.192.in-addr.arpa'


11

As far as conceptual and legibility goes, shells typically are interested in files. Their "addressable unit" is the file, and the "address" is the file name. Shells have all kinds of methods of testing for file existence, file type, file name formatting (beginning with globbing). Shells have very few primitives for dealing with file contents. Shell ...


1

If you install the busybox binary, it includes the nohup command (this will require root access). Busybox may be present, but the command not symlinked, in which case you would need to use busybox nohup command. If busybox is not present, then the easiest way to install is with busybox installer. After that is installed (again, with root privileges), you ...


1

In bash, ksh should work as well, using only shell built-ins: #!/bin/bash # we require array support d=( $(< sample.txt) ) # quote arguments and # build up brace expansion string d=$(printf -- '%q,' "${d[@]}") d=$(printf -- '%s' "{${d%,}}' '{${d%,}}") eval printf -- '%s\\n' "$d" Note that while this holds the entire file in memory in a shell variable, ...


2

One option with Python is to memory-map the file and take advantage of the fact that the Python regular expression library can work directly with memory-mapped files. Although this has the appearance of running nested loops over the file, memory mapping ensures that the OS brings available physical RAM optimally into play import mmap import re with ...


0

would sed -r '/^..../s/:0+/:/g' be ok? (Improved answer from Gilles that keeps first 4 chars untouched)


4

Here's how to do it in awk so that it doesn't have to store the whole file in an array. This is basically the same algorithm as terdon's. If you like, you can even give it multiple filenames on the command line and it will process each file independently, concatenating the results together. #!/usr/bin/awk -f #Cartesian product of records { file = ...



Top 50 recent answers are included