date int64 1,220B 1,719B | question_description stringlengths 28 29.9k | accepted_answer stringlengths 12 26.4k | question_title stringlengths 14 159 |
|---|---|---|---|
1,383,332,844,000 |
Can a command line utility save sub-strings conditionally in different files? I have a file (file.txt) with several lines like the following.
1/1_ABCD4.txt:20020711
1/1_ABCD10.txt:20020731
2/2_ABCD2.txt:20071103
2/2_ABCD5.txt:20071107
3/3_ABCD1.txt:20090225
3/3_ABCD3.txt:20090230
My goal is to save 20020711 together... |
With awk:
awk -F'[:/]' '{print $NF > $1}' file
We split the row using both / and : as separators. The last field ($NF) is what to print, and the first field ($1) is the output filename.
After running for your test input file:
$ head 1 2 3
==> 1 <==
20020711
20020731
==> 2 <==
20071103
20071107
==> 3 <==
20090225
... | Command line - save sub-strings conditionally |
1,383,332,844,000 |
I've recently switched to btrfs for better compatibility with Windows 10 (for which a third-party driver is available). The btrfs partition (on a SATA SSD) was mounted only for /home, and is formatted and mounted as a system partition when my operating system was installed (Pop OS 20.04).
After that I frequently encou... |
The modern and arguably much nicer way is findmnt:
$ findmnt /
# TARGET SOURCE FSTYPE OPTIONS
# / /dev/mapper/cryptroot btrfs rw,relatime,compress-force=zstd:3,ssd,space_cache,autodefrag,subvolid=5,subvol=/
| Show mounted btrfs mounting options? |
1,383,332,844,000 |
cat /dev/urandom generates a random sequence of all possibles "values".
cat /dev/urandom | padsp tee /dev/audio > /dev/null directs these "values" to your audio device, turning them into "random noise" or "random tones" (see: Generating random noise for fun in /dev/snd/)
But how can I do the same but instead of rand... |
You can play around with anything that can do maths (sin especially) and write a number as a character to stdout. For example:
awk --characters-as-bytes 'BEGIN { freq=2200; amp=0.3; for (i=0; i>=0; i++) { printf "%c", 127+ amp*(127.0*sin(2*3.14159265/44100*i*freq)); } }' | padsp tee /dev/audio > /dev/null
Depending ... | How to cat a specific tone to /dev/audio? |
1,383,332,844,000 |
I want to redirect the output of this command firefox &. I know that adding & means that we will run the command in background and when we use it we receive [number of process in background] [PID]. This is what I have done:
firefox & > firefoxFile
But when I open firefoxFile, I found it empty. I don't find [number o... |
If your shell is bash[1], you can try:
exec 3>&2 2>firefoxFile; firefox & exec 2>&3-
It's your shell (eg. bash) which prints that [jobnum] pid background job notification to stderr, not firefox. This kludge temporarily redirects the stderr to the firefoxFile file, capturing into it that notification and whatever fire... | In shell, when I run process in background, how can I get the "[job number] [PID]", redirected to a file? |
1,383,332,844,000 |
Given a pipe of the form C1 | C2, if C2 takes more than one positional argument, is it possible to choose where the output of C1 is going?
Consider the following example.
$ cat myscript
#!/bin/bash
cat $1
cat $2
$ cat world.txt
World
$ echo "Hello" | ./myscript world.txt
World
Hello
I want the final output to be in ... |
You might want to try this:
echo "Hello" | ./myscript /dev/stdin world.txt
So that standard input of ./myscript feeds into the first "cat"
| Choosing the output of a pipe |
1,383,332,844,000 |
I want to sync 2 directories (/src & /dst) to mirror all the files in both of them.
Here is a steps:
sudo rsync -vaP --stats /src /dst -> completed without errors
sudo rsync -vaP --stats /dst /src -> completed without errors
diff -rq /src /dst-> doesn't show any diffs.
du -s /src && du -s /dst shows different sizes ... |
Sparse files may be expanded on copy when the -S flag is not used. (Will make the destination take more space)
Hard links within the tree may be expanded to separate files on copy when the -H flag is not used. (Will make the destination take more space)
Filesystems may have different allocation sizes. A one-byte f... | rsync completed in both directions, but size of directories is different. How it's possible? |
1,383,332,844,000 |
Let's say we have a file having following text:
hello hel-
lo world wor-
ld test test he-
lo words words
If we just use the space as the delimiter, we would have
hello: 1
world: 1
wor:1
ld:1
he: 1
hel-: 1
test:2
lo: 2
words: 2
In other words, how do we process the word separated by 2 lines using a hyphen and treat i... |
This should do it:
sed ':1;/-$/{N;b1};s/-\n//g;y/ /\n/' file | sort | uniq -c
| Find N Most Frequent Words in a File and How to Handle Hyphen? |
1,383,332,844,000 |
The school here wants to teach basic Linux and Unix things like terminal and CLI.
The problem is, installing things is not allowed. So, dual boot is out of the question. Just running windows 8.
Next, the systems aren't powerful enough for any VM. Running ancient systems on 4GB RAM. Currently, the school is using Cygwi... |
Any distro with a live image should work.
A word of caution, though: One COULD use a live linux to mount the windows system disk and then cat /dev/zero > /dev/windowsdisk and thus destroy the windows installation.
A more secure setup would be to boot the PCs from the network and start an already preconfigured system.... | Running Linux on Windows at school without actually installing linux |
1,383,332,844,000 |
The Arch Linux git package installs git-gui under /usr/lib/git-core/.
This means git-gui cannot be launched directly from the terminal without specifying the full path:
$ git-gui
bash: git-gui: command not found
$ which git-gui
which: no git-gui in (/usr/local/bin:/usr/bin:/bin:/usr/local/sbin:/usr/lib/jvm/defaul... |
This is expected behaviour. All git sub-commands are installed to there — you will also find git-commit there, though probably as a link to the main binary for efficiency these days — and the main git command knows where to find them.
Any executable git-X there becomes available as git X automatically, and that's the ... | How to properly solve "git-gui: command not found" on Arch Linux? |
1,383,332,844,000 |
I am wondering about the way the redirection <<< works in bash.
I understand that it redirects the chain after it to the command before as if the content was in virtual file. Examples
$ cut -d. -f1 <<< A.B
A
$ cut -d. -f1 <<< 'A.B
> C.D'
A
C
But I don't understand what it does when used multiple times. Example
$ c... |
<<< redirects the stdin. If you redirect stdin and then redirect it again, the first redirection gets lost.
If the command has a way of saying "process stdin", which e.g. for cat is a dash, you can prepend a line in this way:
cat - input_file <<< 'virtual line'
| Use of multiple <<< |
1,383,332,844,000 |
Extract of lspci -tvv on a server with GPUs:
-+-[0000:b2]-+-00.0-[b3-b8]----00.0-[b4-b8]----08.0-[b5-b8]----00.0-[b6-b8]--+-05.0-[b7]----00.0 NVIDIA Corporation GP104GL
\-0d.0-[b8]----00.0 NVIDIA Corporation GP104GL
What is the format rela... |
Bus can be connected to other buses, and cascade; in your case, you have a root device (no longer visible in the diagram), to which a succession of bridges (with device numbers 00) connect successive buses (b2 to b8), to which the two GPUs are connected.
You can get more information on the devices by dropping the -t; ... | How to interpret lspci -tvv output |
1,383,332,844,000 |
I run both regular Chrome and Chrome Canary (from now on, Canary). Sometimes I want to kill all subprocesses, Google Chrome Helper, of Canary. The problem is that they have the same name as the subprocesses of regular Chrome so killall "Google Chrome Helper" would kill both Canary's and Chromes' subprocesses.
How can,... |
Try using the -P option of pkill:
-P ppid Restrict matches to processes with a parent process ID in the
comma-separated list ppid.
| How can I kill all child processes of a certain process from the command line? |
1,383,332,844,000 |
The sequence of commands
mkdir -p BASE/a/b/c && cp -a --target-directory=BASE/a/b/c /a/b/c/d
creates a subdirectory a/b/c under BASE, and then copies the directory tree at /a/b/c/d to BASE/a/b/c.
One problem with it is that it entails a lot of repetition, which invites errors.
I can roll a shell function that encapsu... |
With pax (a mandatory POSIX utility, though not installed by default in some GNU/Linux distributions yet):
pax -s':^:BASE/:' -pe -rw /a/b/c/d .
(note that neither --target-directory nor -a are standard cp options. Those are GNU extensions).
Note that with -pe (similar to GNU's -a), pax will try and copy the metadata... | "standard" single-command alternative for `mkdir -p BASE/a/b/c && cp -a -t BASE/a/b/c /a/b/c/d`? |
1,383,332,844,000 |
I copied a file to my Ubuntu vm with a backslash in the name, and I cannot figure out how to rename the file, e.g. mv .\Dockerfile Dockerfile -- the command line does not like that syntax for the filename but I'm not sure how to escape the .\Dockerfile
|
You need to escape the backslash:
mv \\Dockerfile Dockerfile
| mv - how to escape backslash in file name? |
1,383,332,844,000 |
Background
I'm running a larger one-line command. It is unexpectedly outputting (twice per iteration) the following:
__bp_preexec_invoke_exec "$_"
Here is the pared down command (removed other activity in loop):
for i in `seq 1 3`; do sleep .1 ; done
note: after i have played with this a few times it inexplicably s... |
Seems like __bp_preexec_invoke_exec is part of https://github.com/rcaloras/bash-preexec/blob/master/bash-preexec.sh. And it seems like that there is a bug in that script.
That project adds 'preexec' functionality to bash by adding DEBUG trap, I did not test, but I can imagine that it might not work properly in the way... | Bash `sleep` outputs __bp_preexec_invoke_exec |
1,383,332,844,000 |
When I run a command like tail ~/SOMEFILE I get, for example:
testenv@vps_1:~# tail ~/SOMEFILE
This is the content of SOMEFILE.
But what if I want to have a carriage return between: testenv@vps_1:~# and the output of: This is the content of SOMEFILE.
So the final result would be like this:
testenv@vps_1:~# tail ~... |
The simplest option would be printing manually those extra newlines, something like:
printf '\n\n\n'; tail ~/SOMEFILE
But if you want to:
Do this just for tail
Not write extra commands with every tail invocation
Have a simple yet full control over the quantity of newlines
then I recommend you to add a function to y... | Display console output 1 or more lines below |
1,383,332,844,000 |
I'm using a grep regex search in a bash script, that does contain quite a lot of search terms.
some commands \
| grep -E 'search1|search2|search3|search4|search5|search6|search7|search8|search9|search10'
is it possible to break this command to make it more readable?
so it would look somehow like this:
some commands ... |
Refer to option -e
some commands \
| grep -E -e 'search1|search2|search3|search4|search5' \
-e 'search6|search7|search8|search9|search10' \
-e ...\
-e ...
| How to break a grep regex search pattern |
1,383,332,844,000 |
I have a directory of files with filenames of the form <num1>v<num2>.txt. I'd like to find all files for which <num1> is a duplicate. When duplicates are found, we should delete the ones with smaller <num2>.
Is this possible? I could easily write a python script to handle this, but thought it might be a nice applic... |
You could do something like:
files=(<->v<->.txt(n))
typeset -A h
for f ($files) h[${f%%v*}]=$f
keep=($h)
echo rm ${files:|keep}
(remove echo if happy)
<->: any sequence of digits (<x-y> glob operator with no bound specified)
(n): numeric sort
${f%%v*}: standard/ksh greedy pattern stripping from the end.
${files:|kee... | zsh globbing - Find files with duplicate filename strings |
1,383,332,844,000 |
I'm trying to use setfattr, but always get Operation not supported
In my home directory, I'm doing the following:
touch delete.me
setfattr -n naomi -v washere delete.me
This returns setfattr: delete.me: Operation not supported.
My home directory is ext4 and delete.me definitely exists. I'm on Fedora 25. Any idea why ... |
You can't just use any name. You need to select a namespace. For arbitrary attribute name, you'd need to use the user namespace:
setfattr -n user.naomi -v washere delete.me
(see man 5 attr for details).
For ext4, the ext_attr feature must be enabled (on by default). Check with:
sudo debugfs -R stats /dev/block/device... | Cannot set file attribute |
1,383,332,844,000 |
I'm downloading a video as follows
$ youtube-dl url_to_video
The download of the file is very slow
33.1% of 301.31MiB at 19.75KiB/s ETA 02:54:03
It was usually faster.
Could you identify with command-line tools where is the bottleneck (the hop where the speed rapidly slows down)? The command-line tool, should be able... |
If you have the tools timeout, traceroute and bing installed this script may help.
What this does is to iterate down a traceroute listing, and compare the packet speed to the "current" host with the packet speed of the previous host. This difference (if any) is then reported to the user.
It requires a target hostname.... | Identify the slow hop when downloading video |
1,383,332,844,000 |
I am trying to use awk command to find line(s) which the third columns is not digit/date? Suppose there is a file comma "," field separated, has three columns and as code "," measure "," dd/mm/yyyy,
97xx574,26.7,12/30/1997,
97xy575,18,12/30/1997,
code,meas,EXAMDATE,
B529ui,28.2,12/30/1997,
B530sx,26.4,12/30/1997,
J487... |
How about this. Where 3rd field does not consist of 0-9 or /, print the line (which is the default action : no need for a print $0.
$3 = third field
!~ = where does not (!) match regular expression
/ = mark start of regular expression
^ = match start of field
[0-9/]+ = match any of the 0123456789/ characters at lea... | How I can find line(s) which the third columns is not digit/date? |
1,383,332,844,000 |
I have folders setup like this:
/path/to/directory/SLUG_1/SLUG_1 - SLUG_2 - SLUG_3
SLUG_2 is a year, and it may have a letter after the year, like "1994" or "2003a".
I would like to rename those files to:
/path/to/directory/SLUG_1/SLUG_2 - SLUG_3
I'm getting pretty close with this command:
find $root -mindepth 2 -maxd... |
Another answer, using GNU find to handle the renaming. This method is robust regardless of what characters may be in the filename.
If I understand your use case rightly, you want to rename directories that start with the full name of their parent directory. In other words, if your directory is named like so:
/some/p... | Batch rename folders with a single bash command |
1,383,332,844,000 |
I am facing a challenging issue in Linux where I need to print a number that is divisible by 4.
The following below helps me print an even number, but not divisible by 4:
echo 5 | awk -F, '$0%2{$0++}1'
Output:
6
I am not sure how to go about this, but perhaps if I use a while loop to add/increment to the initial val... |
With awk:
echo 5 | awk '{$0=int($0/4+1)*4}1'
Explanation:
$0/4+1 the value is divided by 4 and the result incremented by 1.
int(n) this is then rounded down by awks int().
n*4 now we only have to multiply that with 4 to get the next higher number divisible by 4.
{...}1 the 1 at the end will just print the value.
Th... | How to print a number that is divisble by 4 working upwards (while loop) or awk |
1,383,332,844,000 |
I have this setup where I have computer with ssh and a display where I have a user logged in to terminal. What I want to do is send commands like I was using that local session with keyboard. I tried to echo to /dev/tty1 but it just shows what I typed instead executing it. Which makes sense. The system only has bash s... |
The TIOCSTI ioctl can inject characters into a terminal, or see instead uinput on Linux to generate keyboard (or mouse!) input.
ttywrite.c - sample C implementation
Term::TtyWrite - Perl implementation
$ sudo perl -MTerm::TtyWrite \
-e 'Term::TtyWrite->new("/dev/pts/2")->write("echo hi\n")'
| Send commands to another terminal |
1,383,332,844,000 |
I've noticed that some Linux configuration files (e.g. /etc/samba/smb.conf) expect you to enter the actual settings (key value pairs) in a particular "section" of the file such as [global].
I'm looking for a terminal tool/command which allows you to append lines to a specific section of a specific configuration file. ... |
You can do the task by sed directly, for example:
sed '/^\[global\]/a\my new line' /etc/samba/smb.conf
NOTE: This is not a solution because such line can be in config already. So firstly you should to test whether is the line present.
| Appending a line to a [section] of a config file |
1,383,332,844,000 |
I'd to Prefix my files (.dat) like this :
CLY_BIZ_COM_PERD.dat -> 20160622CLY_BIZ_COM_PERD.dat
I have tried the following:
key=`date "+%Y%m%d"`
for i in $(ls /Path/*.dat); do mv ${i} "${key}${i}" ;done
But this command suffix my files and not prefix it.
How can I do this?
|
Two changes to your current script:
don't parse ls; instead rely on the shell's globbing
because the files are in a subdirectory, either cd there first and run the loop, or use basename and dirname to pull out the directory and filename portions of the file before adding the prefix.
(Note: I also changed your "/Path... | Rename file (Prefix) with full path? |
1,383,332,844,000 |
Say, I have a "Quick&Dirty" Perl script in a gui text editor, and I start the Perl interpreter in a terminal window which is running Bash. I can copy-paste the Perl script to the terminal & press CTRL-D to execute it with Perl. Perl will interpret the script and execute it.
Sometimes, there is a typo in the script, wh... |
This is not an answer, but maybe it's an acceptable work-around:
alias p='perl; echo hit control-d again; cat > /dev/null'
Then, if your perl script exits prematurely, you'll harmlessly paste the remainder to /dev/null; if the perl script succeeds, you'll see your friendly reminder and hit control-d to exit the cat c... | Can the Bash shell "Ignore" Excess copy-paste text? |
1,383,332,844,000 |
Folks, I want to know if there exists a command that just highlight some portions of the input text, rather than filtering it like grep does.
To give an example, suppose the following input text:
foo bar
gaz das
xar
grep "bar\|gaz" input would print the first two lines, highlighting bar and gaz, but would not displa... |
USE:
egrep --color 'pattern|$' file
or if you want using grep
grep --color -E 'pattern|$' file
"pattern|$" will match lines that have the pattern you're searching for AND lines that have an end -- that is, all of them. Because the end of a line isn't actually any characters, the colorized portion of the output w... | Pattern highlighting command [duplicate] |
1,450,025,459,000 |
Why can't I use if($l =~ $ARGV[0]) but I can use if($l =~ /$ARGV[0]/g?
first case
$ perl script.pl '/^[\w]/g'
second case
$ perl script.pl '^[\w]'
|
Strings and regexes are different primitive types in perl, and all variables placed in the @ARGV array are simply strings given to the program by the kernel at startup; $ARGV[0] is a scalar string, and not a regex.
When you do if($l =~ $ARGV[0]) and $ARGV[0] is '/^[\w]/g' this is equivalent to if($l =~ '/^[\w]/g') ins... | Why can't I pass a regex in @ARGV on the command line? |
1,450,025,459,000 |
I have process which created multiple PID's. I want to kill all those PID's. I have tried
pkill <process_name>.
But PID not getting killed as they were wait to resource releasing.
I have managed to get PID list with
ps -ef | grep <process_name> | awk '{print $2}'
which gives process ID list but how can I kill all ... |
You could pipe the output to xargs e.g.
ps -ef | grep <process_name> | awk '{print $2}' | xargs /bin/kill
But why doesn't your pkill command work?
| How to kill line of PID? |
1,450,025,459,000 |
I am wandering if there is a way to read the full output of a command when it uses more than the screen. I am currently having to output the command into a file, and then using nano to scroll through it.
E.g. $ ls -Al /etc/ only displays the end of the output and cuts of the rest.
|
You need to use less less is a pager, it allows you to view a page at a time. e.g.
command | less
ls -Al /etc | less
The most common command while in less are:
enter advance one line
space advance one page
q quit / exit help
h help
see man less for more info, like how to search.
| Scroll through command output without a temporary file |
1,450,025,459,000 |
I want to execute these two timeout command on the same command but with a different time and instructions. So
timeout --signal=SIGINT 5s command
timeout --signal=SIGKILL 10s command
How to append them in one line?
|
timeout --signal=SIGKILL 10s timeout --kill-after=5 --signal=SIGINT 5s command
| timeout pipeline |
1,450,025,459,000 |
I really don't know what are the advantages of running applications in the background.
Something like Application & via command line.
Why exactly do we run applications in background and when should I decide to do so?
|
Generally applications that take too long to execute and does not require user interaction are sent to background so that we can continue our work in terminal.
Jobs running in background are treated same as jobs running in foreground except that their STDOUT, STDIN and STDERR varry.
If you have a job that take too lon... | What is/are the advantage(s) of running applications in backgound? |
1,450,025,459,000 |
For example, I have the following output from command:
loom@loom:$ history | grep MAKE
219 ../build.sh -DCMAKE_BUILD_TYPE=Debug ..
909 history | grep MAKE
How to write a command, that start the first command from the list? Also, I'd like to know how to start n-th command from output of history | grep something?... |
See those numbers on the left of the output? You can use them to refer to that command with shell history expansion; ![number] in most shells.
This works both in bash and zsh:
$ echo "hello"
hello
$ history | grep hello
5057 echo "hello"
$ !5057
echo "hello"
hello
$
| How to start first command from the list printed by command 'history | grep something' |
1,450,025,459,000 |
Whenever I type in a bash command longer than about half the width of the shell window I'm in, the command breaks like it would if I filled the whole screen
3rd command in image - typed a few xs and got the expected result.
4th command - typed a load more xs, and the command broke back to the start as though it had ... |
I think that your tty is reporting the wrong tty size. Try running
pi@raspberrypi$ stty -aF /dev/ttyO0
There you will see how many rows and columns the tty thinks it has. This size should match the size set in putty. You can also change parameters, such as number of columns, using stty. The command would be something... | When a command is over half the terminal size it breaks |
1,450,025,459,000 |
I've got some large mailboxes and using Thunderbird, that means that I have several mbox files. These single files contain all e-mails in a particular folder. Now, I would like to get some data on the senders in a particular folder. My ideal statistic would be to get all unique senders, and the number of times their e... |
First, we need to reliably get the From header, which can be done with a restrictive grep regular expression.
% grep --no-filename --ignore-case '^From:' test.eml
From: [email protected]
Next we need to count the number of occurrences, which can be done with uniq -c (which requires a sorted list).
% grep --no-filenam... | Creating a list of unique senders from Thunderbird mail files through the command-line |
1,450,025,459,000 |
I've got this directory full of images, and I can do this:
echo *.jpg
image1.jpg image2.jpg image3.jpg # and so on
How can I get the output in a plain text file in this format?
image1.jpg
image2.jpg
image3.jpg
|
Avoid using ls, bash globs can do it better
printf '%s\n' *.jpg >output_file
| Index names of all the files in a plain text file |
1,450,025,459,000 |
I am attempting to force powertop to run when I log in by using the Startup Applications wizard in Ubuntu. Under the 'Command' entry, I've placed gnome-terminal -x /home/***/Documents/programming/scripts/powertop.sh. It's using a one-line bash shell script:
echo "******" | sudo -S powertop
This inputs my superuser pa... |
Assuming your powertop is in /usr/sbin, you can use sudo /usr/sbin/powertop with no password. To do this you need to run visudo and append the followind line, substituting yourusername with the real one:
yourusername ALL=(root) NOPASSWD: /usr/sbin/powertop
| How can I adjust this short shell script to fit my needs? |
1,450,025,459,000 |
I want to try to setting up a headless (terminal-only) Ubuntu Linux server, and am trying to find resources to get started. I've been a GUI Linux/Windows user for a while now, and have run through a tutorial to setup a server on an Ubuntu desktop (with the GUI), but the biggest hurtle I found was when I tried to only... |
First, I'm going to define some things for you so you get a feel for what application is doing what when it comes to web servers.
Apache is an HTTP web server and allows you to serve static HTML and text files "like the Internet". Your web server will take care of inbound requests and all the other stuff you don't rea... | Recommended Resources To Get Started With Terminal-Only Linux Server? |
1,450,025,459,000 |
The file contains:
dateutkfilename25012009
I want to change the position of character 16th to 17th with 18th to 19th. And then change position of character 16th to 19th with 20th to 23rd... so it will be:
dateutkfilename20090125
I've tried to change position of character 16th to 17th with 18th to 19th using below co... |
Here's the answer to your question:
s/^\(.\{15\}\)\(.\{2\}\)\(.\{2\}\)\(.\{4}\)/\1\4\3\2/
But if you can anchor to the end instead, it gets simpler:
s/\(.\{2\}\)\(.\{2\}\)\(.\{4\}\)$/\3\2\1/
Personally, I'd probably do [0-9] instead of . as well:
s/\([0-9]\{2\}\)\([0-9]\{2\}\)\([0-9]\{4\}\)$/\3\2\1/
As usual, there... | Change character position with sed |
1,450,025,459,000 |
I have...
me@computer:~/gutenberg/euclid$ ls
book01.html book04.html book07.html
book10.html book13.html book02.html
book05.html book08.html book11.html
book03.html book06.html book09.html
book12.html
and I want to join all these .html files into the same big file, in order. What command or command sequence c... |
In this particular case cat book??.html > book.html will work fine, if you don't care about proper HTML format.
For a more general case, say you had "book1.html" instead of "book01.html", "book2.html" instead of "book02.html" and so forth. The file names don't sort lexically the same as logically. You can do somethin... | command for joining a series of files together |
1,450,025,459,000 |
I would like to check the Base64 value for an integer. There is a base64 linux command but I don't understand how I can apply it on integers.
I have tried with base64 10 but then I get the error message base64: 10: No such file or directory
I think that the problem can be that Base64 is used for Binary to Textual conv... |
Convert the number into hex than use echo to print the according byte sequence and pipe that into base64. So to encode the integer 10 with base64, you can use:
echo -en '\xA' | base64
To explain the result. The byte 10 has the following binary representation:
00001010
What base64 does is, it chunks those into groups... | How can I check the Base64 value for an integer? |
1,450,025,459,000 |
How to stop stdin while command is running in ash (not bash)?
For example:
sleep 10
type echo hello while sleep is still running
observe hello is in stdout after sleep finishes
Desired:
sleep 10
type echo hello while sleep is still running
observe shell as if nothing was typed in while sleep was running
I expect t... |
stty -echo disable the echo of your terminal, but if you type something, it will be memorized and the shell will get the typed key.
Then, before leaving, stty echo (revert back the echo mode), and drain the terminal input with this program :
#include <stdio.h>
#include <unistd.h>
#include <termios.h>
int main(void)
{... | Stop stdin while command is running |
1,450,025,459,000 |
(This may be a XY problem, more on the context at the end)
Is there any way of programmatically splitting a pdf based on the section titles? That is
from this pdf, produce 2 pdfs, where one contains everything up to the section called "XY", and the second contains all the rest.
I know how to split a pdf based on the... |
Stewart's answer gave me pretty much all the tools, but I made two important edits to their solution:
Use coherent pdf to preserve the table of content (pdftk just delete it),
Make the command split the file in two, instead of splitting the file into as many files as chapters.
Re-using the parser.awk shared by Stewa... | Split pdf document based on section |
1,450,025,459,000 |
There's a way in browsers to query if the user prefers a dark or light theme so that a website developer could adapt the website's colours according to user preference.
Is there also a way to detect that on the command line? Is there a command that outputs light or dark (or some equivalent boolean-valued output indica... |
You can try this command (tested on gnome desktop environment, ubuntu 22.04):
gsettings get org.gnome.desktop.interface color-scheme
It outputs :
'prefer-dark'
OR
'prefer-light'
| Command for detecting whether the system is using a dark or light desktop theme? |
1,450,025,459,000 |
I have two external drives. One of the drives is named "drive2" and it contains a folder named "Music." This folder has the following structure:
drive2/
/Music/
Pink Floyd/
1982 - Album Name/
01 - Track.flac
... |
when rsync transfers the files that got their metadata updated, does the old files get overwritten completely on drive1?
Yes. The default behavior is that the file currently on the destination is copied to a temporary location. Then any necessary updates are done on that copy. Once the update is complete, the cop... | Keeping two folders in sync with rsync |
1,450,025,459,000 |
Let's say I have a file with the following content:
var1='a random text'
var2='another random text'
var3='a third random text'
I know that if I use the command eval like the following I'll store all those variables directly on my shell:
$ eval $(cat file)
Doing that, my shell will create $var1, $var2 and $var3 with ... |
Using a combination of jo (from here) and jq (from here), without creating shell variables or letting the shell interpret the file at all:
jo <file |
jq --arg sq "'" '.[] |= ( ltrimstr($sq) | rtrimstr($sq) )'
This first uses jo to create the JSON document
{
"var1": "'a random text'",
"var2": "'another random te... | Can I directly convert a file that lists multiple variables to JSON using the command line? |
1,450,025,459,000 |
I'm converting images to a single PDF-file using convert utility:
$ convert "document-*.tiff" -compress jpeg -quality 60 "output.pdf"
Resulting document has the following tags set up:
Title: output
Producer: file:///usr/share/doc/imagemagick-6-common/html/index.html
CreationDate: Fri May 21 19:12:24 ... |
You can do it. You need to change the image registry with a -define
For example:
$ magick -compress jpeg -quality 60 -define pdf:Producer="Stackoverflow" -define pdf:Title="Change tags" "*tiff" "output.pdf"
$ pdfinfo output.pdf
Title: Change tags
Author: https://imagemagick.org
Producer: Stack... | Set PDF tags while converting images to PDF with ImageMagick |
1,450,025,459,000 |
I used the $(()) command and I seen this error:
bash: 0: command not found
Why did this error occur?
|
The $(( )) is an arithmetic substitution or arithmetic expansion. Within it, you may do (integer) arithmetic operations, and the shell would carry them out and replace the whole expression with the result of those operations.
You often see it used like in
count=$(( count + 1 ))
Since there is nothing for the shell t... | Why is the output of the "$(())" command 0? |
1,450,025,459,000 |
I have two files.
The first (emails) should be cleaned according to the second (domains).
First is 15 GB, second is 160 MB.
dom=`cat file2.txt | xargs | sed -e "s/ /|/g"` ; sed -r "/$dom/d" file1.txt >> final_file.txt
This command gives me bash: /bin/sed: Argument list too long.
|
Sounds like you just want:
grep -Fvf file2.txt file1.txt > final_file.txt
That is store in final_file.txt the lines of file1.txt that contain none of the lines of file2.txt.
Add the -x option if you want the lines of file1.txt that are not in file2.txt. Or -w to match on words (where bar.com would not match in foobar... | bash: /bin/sed: Argument list too long |
1,450,025,459,000 |
For example, youtube-dl has different ways to install it onto machine. I downloaded/installed it multiple times in not-same ways inadvertently, so that resulted that I have several youtube-dl executables in my $PATH directories, /usr/local/bin/youtube-dl, /home/username/.local/bin/youtube-dl, and /usr/local/bin/youtub... |
Interactively, I would use:
ls -l $(type -ap youtube-dl)
to find the locations and timestamps of all the youtube-dl programs in my $PATH.
Of course, this doesn't work for executables that have spaces in their names, but youtube-dl isn't one of them.
| How to check duplicate commands in $PATH? |
1,450,025,459,000 |
I've really hard time to understand this behaviour:
stackExchange@test:~$ if [[ "two words" =~ \bwords ]]; then echo hi; fi; #(I'd expect this one worked)
stackExchange@test:~$ if [[ "two words" =~ \\bwords ]]; then echo hi; fi; #(or at least this one...)
stackExchange@test:~$ if [[ "two words" =~ \\\bwords ]]; then ... |
The effect of a backslash in the regular expression part of [[ str =~ rex ]] is to quote the following character (exactly like putting it in single quotes), and in bash and since version 3.2, that directs it to do a literal match for it (1). Since b is not special, \b will turn into just b, but '\', "\\" or \\ will tu... | bash conditional expression and backslash escaping [duplicate] |
1,450,025,459,000 |
I used this snippet of code to start a new column after every 20th row and each of the columns is separated by tabs. I took the code from this post and then tweaked it a bit: How to start a new column after every nth row?
awk '{a[NR%20] = a[NR%20] (NR<=20 ? "" : "\t") $0} END {for (i = 1; i <= 20; i++) print a[i%20]}'... |
In awk, expressions that are separated by spaces get joined together. This concatenation is described in the POSIX awk manual in a table of expressions (the formatting on that page isn't very clear, it's easier to read via man 1p awk). a[NR%20] is being joined together with its current value + ""/"\t" + the current re... | Explanation of awk statement |
1,450,025,459,000 |
ls -d .* lists only hidden "items" (files & directories). (I think) technically it lists every item beginning with ., which includes the current . and above .. directories.
I also know that ls -A lists "almost all" of the items, listing both hidden and un-hidden items, but excluding . and ... However, combining these ... |
This has been answered over at Ask Ubuntu, which I will reproduce here:
ls -d .!(|.) with Bash's extended globs (shopt -s extglob to enable)
ls -d .[!.]* ..?* if not
| How can I exclude . and .. when listing only hidden items? |
1,450,025,459,000 |
Whenever I tried to use the sqlcmd command in my terminal im getting and error like
"sqlcmd: error while loading shared libraries: libodbc.so.2: cannot open shared object file: No such file or directory"
|
It seems you didn't install the unixodbc-dev package which depends on the libodbc1 package and contains the missing shared library.
You can install it with
sudo apt update
sudo apt install unixodbc-dev
Related:
Install the Microsoft ODBC driver for SQL Server (Linux)
| Unable to use sqlcmd command shows libodbc.so.2 |
1,450,025,459,000 |
How can I terminate a process upon specific output from that process? For example, running a Java program with java -jar xyz.jar, I want to terminate the process once the line "Started server on port 8000" appears on stdout.
|
That can be accomplished with the following script considering that grep -m1 doesn't work for you:
#!/bin/bash
java -jar xyz.jar &> "/tmp/yourscriptlog.txt" &
processnumber=$!
tail -F "/tmp/yourscriptlog.txt" | awk '/Started server on port 8000/ { system("kill '$processnumber'") }'
Basically, this script redirects ... | Terminate process upon specific output |
1,450,025,459,000 |
I have a Kali VM that is seized up, during booting it says "resuming from hibernation" and does not progress. There is no disk i/o. I am wondering if it is possible to completely delete the files related to hibernation in attempt to force a normal boot. If so where are these files located, or is there another way to ... |
If your VM includes a Linux swap partition, it might contain the hibernation data, so there will not be a file to delete.
Anyway, if you can access the GRUB bootloader of the VM, add the boot option noresume to avoid any attempts to resume from hibernation and execute a full normal start-up instead.
(Some virtualizat... | How to delete hibernation files on deb based system |
1,450,025,459,000 |
Preface
Not sure if this question is within scope of the Unix Stack exchange since it is theoretical in nature. I am willing to move it to a different stack exchange.
Context
In the Unix command prompt, a user can type ; to execute multiple commands in order. If one fails, it will not stop the execution of the next co... |
The theoretical limit on the number of commands that the shell (assuming sh here) can take on a single line is defined in the POSIX standard:
The input file shall be a text file, except that line lengths shall be unlimited. If the input file consists solely of zero or more blank lines and comments, sh shall exit with... | What is the theoretical upper limit of commands a user can execute in one line? |
1,450,025,459,000 |
Is there a backup tool which is "intelligent" enough to notice that a folder or large files may have been renamed between two backups? Maybe even if their location changed (not too complicated)?
Is it clear what I try to ask for?
My backup methods for now have all added the new dirs to the existing backup. How to "cop... |
Yes, deduplicating backup tools like restic and borgbackup would do this.
These would detect that a given chunk of data (not necessarily a whole file) was already present in the older backup and would not store it again. It would also detect the same chunk in other files, so your fifteen copies of the same MP3 file wo... | CLI backup tool |
1,450,025,459,000 |
I am running a Debian stable with Cinnamon graphical interface 3.6.7 and my computer is connected to a multimedia projector. I havea an Intel Graphic card.
The projected image is too big and I can't change neither the place of my multimedia projector nor the place of my wall to reduce the size of the projected image.
... |
Use xrandr to detect the default output. Then you can make a black border:
xrandr --output LVDS --set underscan on --set "underscan vborder" 100 --set "underscan hborder" 100
(not working with intel graphic card)
| Reduce size of my screen with a command line |
1,450,025,459,000 |
I am trying to pass standard input into multiple commands and compare their outputs. My current attempt seems close, but doesn't quite work - plus it relies on temporary files which I feel would not be necessary.
An example of what I would want my script to do:
$ echo '
> Line 1
> Line B
> Line iii' | ./myscript.sh 's... |
Since the accepted answer is using perl, you can just as well do the whole thing in perl, without other non-standard tools and non-standard shell features, and without loading unpredictably long chunks of data in the memory, or other such horrible misfeatures.
The ytee script from the end of this answer, when used in ... | Pass input to multiple commands and compare their outputs |
1,518,190,471,000 |
What if we run commands like rm -rf / or mv / /dev/null or dd if=/dev/random of=/dev/hda on the virtual machine? Will it affect the host machine? Or what the results of running these commands?
|
Virtualization provides a relatively strong separation between the virtual machine and the host. This is provided by kernel features backed up by CPU features. The recent "Spectre" CPU flaw is particularly concerning because it potentially provides a way for attackers to break down some of this separation — but that d... | What if we run commands like `dd if=/dev/random of=/dev/hda` on virtual machine? |
1,518,190,471,000 |
I need to run a lot of similar commands in a quickest possible amount time and using all available resources.
For example my case is processing images, when I'm using following command:
for INPUT in *.jpg do; some_command; done the command is executed one by one and not using all the available resources.
But on the ot... |
GNU Parallel is made for exactly this:
parallel some_command {} ::: *.jpg
It defaults to one job per CPU core. In your case you might want to run one more job than you have cores:
parallel -j+1 some_command {} ::: *.jpg
GNU Parallel is a general parallelizer and makes is easy to run jobs in parallel on the same mach... | run multiple commands at once |
1,518,190,471,000 |
If I run the following command, the command line is cut:
user@host:~$ ps -eo pid,cmd,lstart
Output:
6382 /home/user/bin/pyt Sun Oct 22 18:51:39 2017
How to get the whole command (inclusive all arguments)?
Version: procps-ng version 3.3.5
|
swap columns:
ps -eo pid,lstart,cmd
| ps cuts command, how to get full |
1,518,190,471,000 |
wget can be feeded with -i inputFileURLList and also can use a custom file name with -O customArbitraryFileName.
How can I combine these two capablities so that I feed it with a file containig URL list with a custom file name for each?
|
Write your own trivial shell script and use it as ./get-them.sh < get-then.list
shell script get-them.sh
#!/bin/sh
while read FILE URL; do
wget -O "$FILE" -- "$URL"
done
input file get-them.list
file1 https://unix.stackexchange.com/
file2 https://stackexchange.com/
| How to combine '-i file' & '-O filename' options of wget? |
1,518,190,471,000 |
I was trying to use negation to exclude directories from globbing, but directories still appear in pattern match:
bash-4.3$ ls
file_1.txt testdir
bash-4.3$ shopt extglob
extglob on
bash-4.3$ echo !(*/)
file_1.txt testdir
bash-4.3$
What exactly am I doing wrong ?
Note:I know I can use for loop with [ or fin... |
You can't have a / in the @(...), !(...), *(...)...
The / can only appear between globs, even a[x/y]b is treated as @(a\[x)/@(y\]b). globs are first split on / and each part matched against the content of a directory. When there are x(...) ksh glob extensions, however, there's no splitting on the / that are inside the... | extglob negation not working as expected |
1,518,190,471,000 |
All of the tons of articles I have found so far all seemed to be focused on obtaining a resulting date, which is still useful, but not what I want in this case.
Example link: Unix & Linux SE -
Quickly calculate date differences.
With datediff in that other Q&A, this is more of what I want referring to a date/time dur... |
With dateutils's datediff (not GNU sorry), (formerly ddiff, dateutils.ddiff on Debian):
$ dateutils.ddiff -f '%Y years, %m months, %d days, %H:%0M:%0S' \
'2012-01-23 15:23:01' '2017-06-01 09:24:00'
5 years, 4 months, 8 days, 18:00:59
(dates taken as UTC, add something like --from-zone=Europe/London for the dates ... | How can I calculate and format a date duration using GNU tools, not a result date? |
1,518,190,471,000 |
I've tried to find the existing topics about this theme and I found something but it's not the 100% what I'm looking for and my internet connection is bad last few days so I needed to quit searching and post a new thread...
So my problem is I have a .txt file with many lines (over 50000), every line has 5 letter strin... |
sed -e '/\(.\).*\1/d' yourfile > youroutputfile
| Delete all lines that contain duplicate letters |
1,518,190,471,000 |
For a project, I would like to be able to use arecord to do both at the same time :
Recording what is passed to the microphone.
Playing it at the same time in the speakers.
In order to do this, I thought about starting with :
arecord -f cd -d numberofseconds -t raw | lame -x – out.mp3
but I don't know how to redire... |
This is what I have found :
First, enable audio forwarding to speakers with pactl load-module module-loopback latency_msec=1
Then I record all I want using arecord -f cd -t raw | oggenc - -r -o out.ogg (using mp3 format didn't works)
To finish, I stop audio forwarding using pactl unload-module module-loopback
If you... | Record & Play what comes from the microphone at the same time |
1,518,190,471,000 |
I have a C executable that takes in 4 command line arguments.
program <arg1> <arg2> <arg3> <arg4>
I'd like to create a shell script that continually runs the executable with arguments supplied by text files. The idea would be something like this:
./program "$(< arg1.txt)" "$(< arg2.txt)" "$(< arg3.txt)" "$(< arg4.txt... |
while
IFS= read -r a1 <&3 &&
IFS= read -r a2 <&4 &&
IFS= read -r a3 <&5 &&
IFS= read -r a4 <&6
do
./program "$a1" "$a2" "$a3" "$a4" 3<&- 4<&- 5<&- 6<&-
done 3< arg1.txt 4< arg2.txt 5< arg3.txt 6< arg4.txt
That runs the loop until one of the files is exhausted. Replace the &&s with ||s to run it until... | Pass multiple command line arguments to an executable with text files |
1,518,190,471,000 |
I need to remotely install a program on a Linux computer. I do:
./configure
make
make install
However I seem to get issues when I run ./configure (it's a separate problem) where the configuration screen essentially freezes; it doesn't move past a certain check. I need to stop the configuration so I do Ctrl+z, and tha... |
Control+ Z suspends (TSTP/SIGSTOP signal) the most recent foreground process, which returns you back to your shell. From the shell, the bg command sends the suspended process to the background while the fg commands brings it back to foreground. Try Control+C, which sends SIGINT, killing the process. Some software rea... | How to stop ./configure script? |
1,518,190,471,000 |
I currently have 2000 user directories and each of these directories have sub directories.
user_1
---> child1
---> child2
user_29
---> child37
---> child56
etc
I need to loop through all of the user folders and then through each of the child folders and rename the child folders with a prefix 'album_'. My end structure... |
Try:
find . -maxdepth 2 -mindepth 2 -type d -execdir bash -c 'mv "$1" "./album_${1#./}"' mover {} \;
Notes:
To form the name for the target directory, we need to remove the initial ./ that will be in the directory name. To accomplish that, we use the shell's prefix removal: ${1#./}.
We use -execdir rather than -exe... | For all directories - rename all subdirectories with a prefix |
1,518,190,471,000 |
I have a long list of data files that I need to copy over to my server, they have the names
data_1.dat
data_2.dat
data_3.dat
...
data_100.dat
Starting from data_1.dat, I would like to get all the files where the number is increased by 3, i.e. data_4.dat, data_7.dat, data_10.dat, ...
Is there a way to specify this? Ri... |
On Linux:
printf -- '-get data_%d.txt\n' $(seq 1 3 100) | sftp -b - [email protected]
On BSD (with no seq(1) in sight):
printf -- '-get data_%d.txt\n' $(jot 100 1 100 3) | sftp -b - [email protected]
| sftp: command to select desired files to copy |
1,518,190,471,000 |
I am using a ssh command executor in java which runs the command and gets the output in stderr, stdout and an integer exit value. I am trying run a command with timeout like,
timeout 5s COMMAND
Is there a way to get a response in the stderr or the stdout so that I can know whether the command was timed out or no... |
From man timeout:
If the command times out, and --preserve-status is not set, then exit
with status 124. Otherwise, exit with the status of COMMAND. If no
signal is specified, send the TERM signal upon timeout. The TERM sig‐
nal kills any process that does not block or catch that signal. It may
... | How to get the output of timeout command without using a shell script |
1,518,190,471,000 |
I am trying to get libnotify (notify-send) to pop-up a notification once a certain character is found while I tail a log file.
Without grep it works fine ...
Here is my code:
tail -f /var/log/mylogfile | grep ">" | while read line; do notify-send "CURRENT LOGIN" "$line" -t 3000; done
When I include grep it passes no... |
This page explains grep and output buffering, in short you want to use the --line-buffered flag:
tail -f /var/log/mylogfile | grep --line-buffered ">" | while read line; do notify-send "CURRENT LOGIN" "$line" -t 3000; done
About the font, this AskUbuntu question mentions it's not officially possible, but describes a ... | libnotify with bash and grep |
1,518,190,471,000 |
I have a bash script for copying two files from a remote machine (that I cannot control), stored in a a path that needs root access. Here it is:
ssh administrator@host "mkdir ${DIR}"
ssh -t administrator@host "sudo su - root -c 'cp /path/for-root-only/data1/${FILENAME} ${DIR}/'"
ssh administrator@host "mv ${DIR}/${FIL... |
You don't need to do it as a HERE document (which is what the << stuff does).
You can simply do ssh remotehost "command1; command2 ; command3"
e.g.
% ssh localhost "date ; uptime ; echo hello"
sweh@localhost's password:
Tue Jul 19 08:07:48 EDT 2016
08:07:48 up 15 days, 31 min, 3 users, load average: 0.33, 0.33, 0.... | Execute multiple ssh commands with different switch |
1,518,190,471,000 |
I would like to download and run a script in the background so the task is independent of the shell and its exit. Moreover this script should be run as sudo, using:
echo MY_PWD | sudo -u MY_USER -S ...
So it just needs a single line of code in my SSH-Session, which does the authentication and creates the background t... |
This is wrong syntax in bash:
nohup ./NEW_SCRIPT_NAME.sh & && rm NEW_SCRIPT_NAME.sh
From Shellcheck:
Line 1:
nohup ./NEW_SCRIPT_NAME.sh & && rm NEW_SCRIPT_NAME.sh
^-- SC1070: Parsing stopped here. Mismatched keywords or invalid parentheses?
You can not simply run something & && something... | Submit password with sudo and execute script with nohup |
1,518,190,471,000 |
I have a question about groupadd, specifically with password (-p). It says it is not recommended, "This option is not recommended because the password (or encrypted password) will be visible by users listing the processes." Can someone give me a broader explanation? How will a user see the password when viewing the pr... |
It's possible for a user on the system (or a monitoring program that captures ps output) to see the password as a parameter to the groupadd process -- if the user or monitor "happens" to run ps while the groupadd process is running. The risk of that happening is small (the groupadd process will likely finish running f... | groupadd -p Not Recommended? |
1,518,190,471,000 |
I'm investigating the relationship between bash and emacs shorcuts. Someone told me that the reason why they're similar is that bash uses emacs as its command line interpreter. However, I haven't found any evidence that supports this thesis.
I know there are "edits modes" in bash and one of them is emacs. But, is it t... |
The short answer is "no". bash's command-line processing is implemented mostly in bashline.c and its copy of readline, which supports vi-like and Emacs-like behaviours. Emacs itself is written mostly in Emacs Lisp; using it to implement bash would be quite involved since Emacs Lisp isn't designed to be used without Em... | Is bash command line interpreter implemented on emacs? |
1,518,190,471,000 |
I have a directory (let's call it "Movies") which contains many files and folders. I have a long list of file names in a .csv file (around 4000 entries) which refer to files which are located somewhere within the Movies directory sub-folders.
How can I search the Movies directory recursively for the files listed in th... |
while IFS=, read -r file rest
do
find /path/to/movies_dir -name "${file}" -exec cp '{}' /path/to/Sorted_Media/ \;
done < mylist.csv
That assumes file names don't contain wildcard characters (?, [, * or backslash).
| Search a directory recursively for files listed in a csv, and copy them to another location |
1,518,190,471,000 |
I am trying to make a shell script to print the amount of time user was logged into the system but I encountered a too many arguments error. I tried many methods from the internet but none worked. Can someone spot the mistake?
#!/bin/bash
lt=`who | grep "jeevansai" | cut -c 35-39`
lh=`echo $lt | cut -c 1-2`
lm=`ech... |
You are assuming that the output of who | grep jeevansai will be a single line, which is wrong.
++ who
++ grep jeevansai
++ cut -c 32-34
+ ld='31
31 '
This is telling you that the command
ld=`who | grep "jeevansai" | cut -c 32-34`
set the variable ld to "31 31", rather than to a single number as you were expecting... | error ./c.sh: line 24: [: too many arguments in shell program |
1,518,190,471,000 |
How can I let the openssl s_server to reply to every http(s) request directly from the command line or the server it self (the server is using centOS)? is that possible?
from the -help command for the openssl s_server I see that there is the -HTTP flag which should be used for :
-WWW - Respond to a 'GET /<p... |
With -WWW or -HTTP, s_server acts as a static content HTTPS server using files in the current directory. Here's my full set up for demonstration.
$ openssl req -x509 -nodes -newkey rsa -keyout key.pem -out cert.pem -subj /CN=localhost
$ echo 'hello, world.' >index.txt
$ openssl s_server -key key.pem -cert cert.pem -W... | How to let openssl respond to http/s get directly from command line while listenning |
1,518,190,471,000 |
I created a text file and put some email addresses in it. Then I used grep to find them. Indeed it worked:
# pattern="^[a-zA-Z0-9]+@[a-zA-Z0-9]+\.[a-z]{2,}"
# grep -E $pattern regexfile
but only as long I kept the -E option for an extended regular expression. How do I need to change the above regex in order to use gr... |
Be aware that matching email addresses is a LOT harder that what you have. See
an excerpt from the Mastering Regular Expressions book
However, to answer your question, for a basic regular expression, your quantifiers need to be one of *, \+ or \{m,n\} (with the backslashes)
pattern='^[a-zA-Z0-9]\+@[a-zA-Z0-9]\+\.[a-z... | What is the email matching regex in basic regex for grep? |
1,518,190,471,000 |
I would please like some help with this command because I didn't find anything in documentation that can cover everything I want.
I have some variables that are global, so I would prefer to keep them out of awk.
chr="chr10"
inpfile="exome.bed"
outfile="exons_chr.bed" -> which should be composed according t... |
You have various options...
To pass shell variables to awk and use them in string comparison and let the shell create the file:
awk -v chr="$chr" '$1==chr' "$infile" > "exons_${chr}.bed"
To additionally let awk do the output into the file:
awk -v chr="$chr" '$1==chr { print > "exons_" chr ".bed" }' "$infile"
| awk with variables in condition and in output redirection file |
1,518,190,471,000 |
Is there is a functionality in Linux that allows you to reference multiple files as one?
For example:
linux.txt.0, linux.txt.1, linux.txt.2, linux.txt.3 can be seen as separate files or as linux.txt
A useful example:
echo linux.txt
should print the contents of linux.txt.0, linux.txt.1, linux.txt.2, linux.txt.3 in tha... |
The easiest way to do that kind of thing is to use the shell's globbing and/or brace expansion features:
cat linux.{0..3}.txt
or
cat linux.*.txt
As others have explained, cat does not load the whole file into memory, it will just read a few bytes from it, print them to screen and repeat until everything has been rea... | Linux split separate files on disk but see as one |
1,518,190,471,000 |
I have a log file that gets updated when my script runs. The script will insert "Start of script" text when it starts and "End of script" text when it finishes running. I am trying to capture the text between the "Start of script" and "End of script". The most recent entries are at the bottom of the log.
Using the ... |
Perhaps a little state machine:
tac file |
awk '/End of script/ {p=1} p {print} p && /Start of script/ {exit}' |
tac
| Use awk to find first occurrence |
1,518,190,471,000 |
What's wrong with this command:
nmcli c up uuid "$nmcli -t -f uuid c"
How can I fix it?
"$nmcli -t -f uuid c" is a uuid needed after nmcli c up uuid.
|
nmcli c up uuid "$(nmcli -t -f uuid c)"
Use backticks or $(cmd) for commmand substitution
Note that nmcli -t -f uuid c can print out more than one uuid. I didn't test it yet, but the command above might not work then. If so, you should make sure that you are using the right uuid like that:
nmcli c up uuid `nmcli -t... | Using a string parameter in terminal |
1,518,190,471,000 |
I have observed that there are often subtle and often annoying differences between the default versions of certain command line tools like paste and sed on modern distributions of Linux versus OSX. This leads to answers that do not work on OS X even though they will work on almost any Linux distribution.
So I wonder... |
As mentioned in a comment, Apple makes the source code of its versions of these tools available. Many common commands are in the "shell_cmds" package, while paste and sed are in "text_cmds". You can get the source code and compile.
Virtually all of them work fine on Linux systems, although you often have to jump into ... | Is it possible to obtain OS X versions of Unix tools on modern Linux distributions (like Ubuntu or RedHat)? |
1,518,190,471,000 |
I am trying to pass arguments to a bash script and then to a php script, I have literally looked at 30+ links, and tried over a dozen examples, and I for whatever reason have not been able to get the following to work, I am seriously frustrated, any help is so very much appreciated.
For the sake of this question, lets... |
Would have been enough to have a look at the "QUOTING" block in bash's man page... (to find a pointer to the PARAMETERS block where it is explained)
/usr/bin/php test.php "$@"
| Pass bash script arguments in double quotes to php cli script |
1,518,190,471,000 |
Linux supports sparse files aka 'file with holes'
Note following commands
alias mystat='stat -c "%n: %B*%b blocks %s bytes"'
dd if=/dev/zero bs=1024k seek=4096 count=0 of=file-with-holes
ls -l file-with-holes
-rw-r--r-- 1 root root 4294967296 Feb 25 18:33 file-with-holes
mystat file-with-holes
file-with-holes: 512*... |
cp --sparse=always file-without-holes another-file-with-holes
Example:
$ cp --sparse=always file-without-holes another-file-with-holes
$ du --apparent-size another
16384 another-file-with-holes
$ du another-file-with-holes
0 another-file-with-holes
| Looking for a "undo" for file with holes (GNU) |
1,518,190,471,000 |
I'm using the default terminal command prompt on Ubuntu 12.04. When I'm doing something on the prompt (as opposed to editing in VI) the scrolling starts when the text reaches bottom of the screen. I don't like that because I have to keep my eyes always at the bottom of the screen. I would prefer if there were an optio... |
I'm using gnome-terminal as my console and it respects the vt100 set scroll region Control character Sequence.
$ cat setscroll.sh
function min(){
if [[ $1 -le $2 ]]; then echo $1; else echo $2; fi
}
function max(){
if [[ $1 -ge $2 ]]; then echo $1; else echo $2; fi
}
function setscrollregion(){
CLR="\033[2J"
... | Start scrolling command prompt when filled until a particular fraction |
1,518,190,471,000 |
I have a largish directory with filenames formatted like
Some_Folder-(FOL001)-clean
what I'm trying to do is display the pattern between the brackets at the start like
FOL001 Some_Folder-(FOL001)-clean
so it can be piped into sort
So far what I have is
ls | sed -n -e 's/.*\(\-([A-Z]\{3,4\}[0-9]\{3,4\})-\)\(.*\)/\1 ... |
You can move the grouping parentheses inside the presented parentheses.
This would do:
ls | sed -nre 's/.*-\(([A-Z]{3,4}[0-9]{3,4})\)-.*/\1 \t \0/p'|sort
I also use -r for regexp, it's easier to write brackets and parentheses.
With this option, grouping parentheses are (,), and actual parentheses are \(,\)
| Sed - string substitution with groupings |
1,518,190,471,000 |
I am running Ubuntu 12.04, which came with Cmake v 2.8.7.
I had need for a more current CMake, so I downloaded the source for 12.8.12.1, built, and installed it per directions. The last step, make install I ran sudoed.
./bootstrap
make
sudo make install
Now I want to run it, but I find that the old version is still... |
You should use the type command to know what is really under its name, i.e.:
type cmake
That might be an alias that run a different version of cmake, or a function with a similar behavior or finally a previously hashed command that in not any more the first one in your PATH, as you experienced.
| 'which' reports one thing, actual command is another [duplicate] |
1,518,190,471,000 |
Both give the output of the command, so what is the semantic difference between the two? Some reading led me to suspect is that $(command) is Bash syntax, and the back quotes are integrated into Unix somehow; is there any truth to this?
|
The two have identical semantics. Backquotes were the earlier form of command substitution, but they are difficult to nest since the opening and closing delimiters are identical, requiring lots of escaping. $(...) solves that problem, as well as being more readable in certain fonts.
| What's the practical difference between `command` and $(command)? [duplicate] |
1,518,190,471,000 |
I needed to display a list of directories sorted by their creation date and I came up with this code snippet that I thought was kind of clever. Is there a more obvious way to do this that I'm missing?
printf "%-20s\t\t\t%-s\n" "DATE" "CASE"
printf "%-20s\t\t\t%-s\n" "----" "----"
find $idir -mindepth 3 -maxdepth 3 -t... |
There is no good, portable method to sort files by their time. The most portable methods are:
If you can assume that file names contain only printable characters, call ls -ltd.
Otherwise, use perl.
This is the classical method to sort files by date with GNU tools. You're assuming that the file names contain no newli... | Any better method than this for sorting files by their creation date? |
1,518,190,471,000 |
Of course I know the command:
iwconfig
which lists devices (and gives info about whether they have a wireless connection). For the purposes of a shell script, I'm really wondering, is there any way to list only the device names that DO have a wireless connection?
Essentially any other iw command (or something similar... |
Try ls /sys/class/net | grep w
| Best way to find the active wireless device |
1,518,190,471,000 |
I'm trying to wget all the images pictures from a website. I thought I knew how to use it, but I guess I don't.
The images I'm trying to get come from here.
The command I'm using is:
wget -prA.png http://gameinfo.euw.leagueoflegends.com/en/game-info/champions/
But I only get a index.html back?
Could somebody explain... |
The web page uses dynamic HTML to display the champion grid content (just look at the HTML source of the page and search for "Champion Grid", the only thing under that is some empty divs. Since wget doesn't do javascript, it won't execute the code that would generate the grid HTML (and link the images).
| Get all images from website |
1,518,190,471,000 |
In Terminal, one can enter 'xkill' as a command which lets you select a window whose client you wish to kill. In fact, it can even be used to kill panels.
How can I restore an xkilled panel in Linux Mint without a reboot?
Something that I generally do in Windows is Ctrl+Alt+Delete and then restart the explorer.exe se... |
Pressing Alt+F2 and then enter cinnamon --replace might fix it.
| How can I restore an xkilled panel in Linux Mint without a reboot? |
1,375,280,881,000 |
CTRL+R allows me to reverse search through the command history which is great but can I also find out from which directory that command was run? I am using C-shell in Linux.
|
If you type history you will get a history of the commands you issued. You can locate the command you want and look at the entries above to see what cd commands are there. This may give you the information you need.
| Can I see in history output from which directory I had actually issued a command? |
1,375,280,881,000 |
I'm trying to send email with an html file as the body (it's actually a cucumber results report if that matters) or an attachment (if sending it as the body does not work) via the command line
I've tried the following based on the mutt example in this answer to another question, but it is resulting in an error.
cat <<... |
If you just want to send Audit_Results.html verbatim, use this syntax:
mutt -e "set content_type=text/html" -s "Your audit results" [email protected] < Audit_Results.html
You won't need to pre-edit Audit_Results.html with mail headers, you can just send it directly.
| Trying to send HTML mail on mac OSX Mountain Lion |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.